Maintain the initial value using ko.mapping.fromJS

How can I prevent new data fetched from an AJAX call using ko.mapping.fromJS from replacing the existing data in my observableArray? I want to append the new data without losing the previous entries.

function ViewModel() {
  var self = this;
  
  self.SampleArray = ko.observableArray([]);
  
  $.ajax({
    ..
    ..
    success: function() {       
       ko.mapping.fromJS(data, {}, self.sampleArray());
    }
  })
}

Answer №1

Ensure to push items into the observableArray instead of replacing them

Data Model:

function ViewModel() {
    var self = this;
    self.sampleArray = ko.observableArray([{
        'Hours': 0.5
    }])
    setTimeout(function () {
        alert('Simulated ajax call')
        var newData = ko.mapping.fromJS(data1)();
        self.sampleArray.push.apply(self.sampleArray,newData) 
    }, 2000);
}
ko.applyBindings(new ViewModel())

Benefits of using push.apply compared to conventional loops:

If you add items one by one to an array / collection (using array.push(item)), subscribers will be notified for each addition causing multiple UI refreshes and impacting performance.

However, by employing array.push.appy, you can add multiple items while notifying subscribers only once.

This is the advantage and utility of the array.push.apply function.

View a working example on Fiddle: here

Another Fiddle showcasing usage with utils.forEach: here

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The error message "Unexpected token < in JSON at position 0" is indicating a SyntaxError in the

I am facing an issue with the API on this specific page. Although the API is working fine on other pages, it seems to be encountering a problem here. I'm not sure what's causing the issue. Below is the code snippet: export async function getStati ...

Is it possible to create a functionality in Google Sheets where a cell, when modified, automatically displays the date of the edit next to it? This could be achieved using a Google

Here is the current code snippet I have: function onEdit(e) { var range = e.range; var val = range.getValue(); var row = range.getRow(); var col = range.getColumn(); var shift = 1; var ss = SpreadsheetApp.getActiveSheet().getRange(row, (col+ ...

Is there a more efficient method for creating HTML with coffeescript / jQuery besides using strings?

Today marks my first attempt at creating a "answer your own question" post, so I hope I am on the right track. The burning question in my mind was, "Is there a more efficient way to generate HTML with jQuery rather than using tag strings?" My goal is to c ...

How do you go about installing the most recent version of a module through Private NPM?

When using a private npm registry, I have noticed that some common commands do not seem to be functioning properly: npm install without specifying a specific @version :: issue npm outdated :: issue npm update :: issue npm view <private-packag ...

I am hoping for JavaScript to perform three distinct actions depending on the names of the files that are currently open in Photoshop

Currently, I am in the process of developing a JavaScript script for Photoshop. The main objective of this script is to prompt the user to choose a folder containing multiple files. Subsequently, the script will open each file within the folder and perform ...

What could be the reason for receiving an undefined user ID when trying to pass it through my URL?

Currently, I am in the process of constructing a profile page and aiming to display authenticated user data on it. The API call functions correctly with the user's ID, and manually entering the ID into the URL on the front end also works. However, wh ...

Consistentize Column Titles in Uploaded Excel Spreadsheet

I have a friend who takes customer orders, and these customers are required to submit an excel sheet with specific fields such as item, description, brand, quantity, etc. However, the challenge arises when these sheets do not consistently use the same colu ...

There appears to be an issue with Mongoose Unique not functioning properly, as it is allowing

Below is the complete code snippet I am using to validate user data: import { Schema, model } from 'mongoose'; import { User } from './user.interface'; const userSchema = new Schema<User>({ id: { type: Number, required: ...

AngularJS interprets expressions in the 'action' attribute

This afternoon I encountered a rather peculiar behavior with AngularJS. If "//" is present in an expression within the "action" attribute of a form, Angular will throw an interpolate error. Take a look at the code snippet below. When you run this code, t ...

Tips on changing the outline color by clicking

I'm working on a simple code where I need to change the outline color when a user clicks on a text field. <input type="text" id="box1" /> <input type="password" id="box2" /> <input type="email" id="box3" /> <input type="submit" ...

Is there a way to obtain metadata for a specific link?

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title><$BlogPageTitle$></title> <meta property="og:title" content=" ...

Node.js does not allow for the usage of `.on` to monitor events until the client has been

I'm currently working on developing a WhatsApp chatbot using the whatsapp-web-js package. However, I am facing some difficulties with implementing it due to my limited knowledge in node JavaScript and async code. let client; //To establish connection ...

The registration feature powered by JQuery is experiencing technical difficulties and not functioning

Having trouble with a registration system on my website at *. When someone registers, it should either show an error message or display "true" if the registration is successful. I have a javascript file (http://pastebin.com/mv9CWZcT) set up to redirect the ...

Load a webpage using javascript while verifying permissions with custom headers

Seeking guidance as a novice in the world of JavaScript and web programming. My current project involves creating a configuration web page for a product using node.js, with express serving as the backend and a combination of HTML, CSS, and JavaScript for t ...

The HTTP request seems to be malfunctioning

When attempting to establish a connection and retrieve data from a PHP file using an AJAX request, it's important to note that the AJAX JS is located on a different website. Here is the script being used: var quer; try { quer = new XMLHttpRequest( ...

Is it possible to change the transition behavior within a Vue component?

Is there a way to modify or replace transitions within a Vue component? I am currently using Buefy components for my website, but I have encountered an issue with certain components like collapse that have a slot with a fade transition that I do not pref ...

Verify email availability in Cakephp by utilizing Ajax techniques

I have been attempting to verify the availability of an email address using Ajax in Cakephp, but unfortunately, it is not functioning as expected. When the form is submitted, it just adds the duplicate email address into the database without any validation ...

Error: Document's _id field cannot be modified

I am new to both MongoDB and Backbone, and I find it challenging to grasp the concepts. My main issue revolves around manipulating attributes in Backbone.Model to efficiently use only the necessary data in Views. Specifically, I have a model: window.User ...

Unlocking the power of AJAX to retrieve information from a database

The success function is not returning any data. Below is the controller code: controller/manageprojects.rb class Manageprojects respond_to :html, :json def fetch_currency_symbol @location = Location.find_by_country(params[:country]) ...

Launching a pre-built React application

I'm facing an issue while attempting to run a pre-existing React App on my Mac locally. I have all the source files and node.js installed on my machine. Upon running npm install, I encountered a massive list of deprecations and npm ERRors that surpas ...