I have a backbone model where I have changed the set method to calculate extra attributes on every set of the model.
According to the docs this should be the way to call super in order to make sure the model is actually saved.
Backbone.Model.prototype.set.call(this, attributes, options);
And it works just as expected, unless I use Collection.create.
My custom set method gets run, but I think the original does not since the collection remains empty. The server receives the correct data and sends the right data back. On both occasions my method gets executed, but the collection is still empty.
Can I change the super call to make it work with Collection.create or is there another way to do the same thing?
Just as I thought, I missed something.
When overriding Model.set() one must put return this;
at the end.
So a model should look like this:
var MyModel = Backbone.Model.extend({
set: function(attributes, options) {
// Custom code...
return Backbone.Model.prototype.set.call(this, attributes, options);
}
});
I'd recommend cracking open a debugger and following it through. Take a look at the Collection.create function and the Model.save function. Note that the create
function calls Model.save
with a success
callback. Model.save
sends the data to the server and also chains to the success
callback at which Model.set
is called.
I'd put breakpoints in the success
callbacks for both of these functions as they are very straight forward and will likely point out your issue.
Finally, if you are able to reproduce the problem with a jsFiddle, it would be really useful in helping us understand the full context of the problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With