开发者

How can I bind this.save to a backbone.js model change event?

I want my model to save to the server every time it changes.

I have tried:

initialize: function() {
    this.bind('change', this.save());
},

I'm new to Backbone so I'm willing to believe there is a better way to achieve this. Basically I want avoid calling model.save at other points in my code by just automatically 开发者_JS百科saving to the server every time the model changes.


Careful with using this.save directly:

this.bind('change', this.save); 

will cause the changed attributes sent with the change event to be passed in to the save method, which will cause a second 'change' event to be fired, and so it will be saved twice.

Instead use:

this.bind('change', function(){ this.save(); });


you are calling this.save immediately instead of passing it through as a callback function.remove the parenthesis on this.save:

initialize: function() {
    this.bind('change', this.save);
},

and your model's this.save method will be passed in as a function reference, allowing it to be called when the model changes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜