I have a backbone collection, that uses a save mixin to do a Bulk save (just a utility method since backbone does not natively support bulk save)
// 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);
}
});
}
};
});
So when I want to a bulk save of the collection, I would be calling
cars.save();
The question I had here was in the success
callback of the ajax
method, I will be calling the onSuccess
method available in the options object to which I will be passing in the arguments.
What is the different between
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
Can someone explain the difference between the 2 scenarios ?
In the first example you just pass the arguments object to that function.
In the second one, you invoke the function using apply. In short, the apply function calls the function with "spread" arguments. That means the your function is called like yourFunction(arg0 /* where arg is a single element from arguments */, arg1, argN, ...) with given "this". For more see the page I pointed out.