Backbone.js Collection.create and overridden Model

2019-05-07 07:29发布

问题:

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?

回答1:

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);
    }
});


回答2:

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.