2016-04-19 42 views
0

我有一個骨幹收集,使用保存混入做批量保存(只是一個實用的方法,因爲骨幹本身不支持批量保存)差異適用與參數

// Cars collection 
define([ 
    'Car', 
    'BulkSave' 
], function(Car, BulkSave) { 
    return Backbone.Collection.extend({ 
     model: Car, 
     save: function() { 
      var options = { 
       ... 
       onSuccess: function(cars) { 
        // do something with cars 
        console.log(cars); 
       } 
       ... 
      }; 

      this.bulkSave(options); 
     } 
    }).mixin(BulkSave); 
}); 
// BulkSave Mixin definition 

define([], function(){ 
    return { 
     save: function(options){ 
      var thisCollection = this; 

      $.ajax({ 
       type: options.type, 
       url: options.url, 
       dataType: 'json', 
       contentType: 'application/json', 
       data: JSON.stringify(options.data), 
       success: function(data) { 
        // data would give me the list of cars 
        // that changed 
        options.onSuccess.apply(thisCollection, arguments); 
       } 
      }); 
     } 
    }; 
}); 

所以當我想批量保存集合的,我會打電話

cars.save(); 

我在這裏是在success回調ajax方法的問題,我會調用onSuccess方法可供選擇的方案對象爲w我將會傳遞這些論據。

什麼是

options.onSuccess(arguments); 
// this logs an arrayList of 3 properties 
// [0] -- the actual list of cars which changed 
// [1] -- 'success' 
// [2] -- the xhr object 

之間的不同VS

options.onSuccess(thisCollection, arguments); 
// When i do this instead 
// it logs 
// the list of cars that changed instead 

有人可以解釋2種情形之間的區別?

回答

3

在第一個示例中,您只需將參數對象傳遞給該函數。

在第二個中,您使用apply調用該函數。簡而言之,apply函數使用「spread」參數調用函數。這意味着你的函數被稱爲像yourFunction(arg0/*,其中arg是來自參數* /,arg1,argN,...的單個元素),並給定「this」。欲瞭解更多,請參閱我指出的頁面。

+0

您的意思是說,如果我的函數有3個參數,那麼這個應用可以按如下方式工作: 'onSuccess:function(cars,successString,xhr){}'在哪裏可以訪問方法內的每個arg? –

+0

是的,確實如此。你會得到3個參數傳遞,你可以很容易地訪問它們,你可以調用option.onSuccess(car,successString,xhr)。 –

+0

這是有道理的。謝謝你清除我的懷疑:) –