简体   繁体   中英

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 attributes?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM