Princa
Princa

Reputation: 447

Knockout.js array append more objects

I am loading data with Ajax, for initial load, I could bind all data by using this to observableArry:

            success: function (result) {
                var mappedData = $.map(result.d, function (item) {
                    return new Applicant(item);
                });
                self.Applicants(mappedData);
            }

The question is when I want to load more to the array, I know how to add one, but what if the next load would be more than 1 object, and I want to bind to array, how could I do that?

self.Applicants.push(mappedData); won't work.

Any suggestions?

Upvotes: 2

Views: 864

Answers (2)

Andrew Whitaker
Andrew Whitaker

Reputation: 126072

I would use:

Array.prototype.push.apply(self.Applicants(), mappedData);
self.Applicants.valueHasMutated();

For general tips & tricks on working with observable arrays, be sure to check out Ryan Niemeyer's article on it.

Upvotes: 1

Adam Rackis
Adam Rackis

Reputation: 83376

If you need to add a bunch of objects to your observable array, I would just set the whole array to its current contents, concated with the new object.

The following should work:

self.Applicants(self.Applicants().concat(mappedData));

Upvotes: 3

Related Questions