简体   繁体   中英

Understand how knockout is interacting with a javascript object with the push.apply

This is probably yet another javascript scope question with a knockout spin. Going through the examples in a book that I purchased in which the author presents an example of a single page application but chooses not to completely explain the javascript as it is not the focus of the book.

My question is how does the function in the success action in the ajax call understand the definition for the nested object used as an argument.

outerobj.myarray.push.apply(outerobj.myarray, data.map(function (nestedobj) { nestedobj.prop1 }))

The main object
var outerobj = {
  view: ko.observable("View1")
  nestedobj : {
           prop1 : ko.observable(""),
            prop2 : "",
            prop3 : ko.observable("")
        },
         myarray : ko.observableArray([])
}

In a later Ajax/Jquery option there is a call to push.apply with a call like this

var getProperties = function ()
 {
 $.ajax("/path", {
  type: "GET",
  success: function (data) {
  outerobj.myarray.removeAll();
  outerobj.myarray.push.apply(outerobj.myarray, data.map(function(nestedobj) { return nestobj.prop1; }))
  outerobj.view("Result");

}
});
}

Array.prototype.push will push values into the 'top' of the array. It can receive a variable number of arguments, such that:

[1].push(2);  //[1,2]
[1].push(2, 3); //[1,2,3]

.apply executes a function from the given scope, applying a given array of arguments. It spreads out the array as arguments to the function. For example:

var arr =[];
[].push.apply(arr, [1,2]);  // this is equivalent to arr.push(1,2);

Finally, .map returns an array... So basically this is a nice way of pushing an array of items into the array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM