Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone.js Collection.create and overridden Model.set

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?

like image 779
Mathias Nielsen Avatar asked Dec 06 '22 19:12

Mathias Nielsen


2 Answers

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);
    }
});
like image 61
Mathias Nielsen Avatar answered Dec 10 '22 11:12

Mathias Nielsen


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.

like image 23
Brian Genisio Avatar answered Dec 10 '22 13:12

Brian Genisio