开发者

Should the state of a backbone.js model be fully stored in its attributes?

Should the state of a backbone.js model be fully stored in it's at开发者_运维技巧tributes?

Can you duplicate a models state by passing its attributes into another model?

Thanks


Yes and Yes.

calling .toJSON() on a model duplicates it's attributes, and this can be passed into another model:

var m1 = new MyModel({foo: "bar", baz: "widget"});
var attrs = m1.toJSON();
var m2 = new MyModel(attrs);

console.log(m2.get("foo")); //=> "bar"
console.log(m2.get("baz")); //=> "widget"


The answer depends on whether you want to persist the state to full extent. You might not want to persist the complete state through your backend- in such cases you can have those data members that you want to persist in the attributes hash and rest of the members as direct data members of model instance and let the default persistence model of Backbone work the way it does. However there is a flipside to having the state defined using attributes as well as model instance members, the data members of an instance are not observable where are members of attribute hash are ie. you can bind observers to change in these attributes, basically that is what the getters and setters provided by Backbone are for. So in a nutshell your entire state ceases to remain observable ie. you can not programmatically detect changes in data members of model instance as state change. This might not bother you if you are detecting state changes to specifically call sync. To resolve the issue, if that does bother you, we can have all the parameters that define the state of model in the attributes hash, so you can reliably detect state change and then override the toJSON function to return a hash of only those attributes that you need to persist. The flipside to this approach is that in many cases when you detect a change in model state it is quite possible that none of the states you wish to persist have been changed. So choose as per your requirements.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜