admin管理员组文章数量:1289508
How can I update the defaults object of a Model?
For example, let's say I have Box object modelled below. It has a default "Colour" attribute set to "#FFF".
Once the user starts interacting with the server, at some point the server passes back a new default colour #000. I want all new boxes instantiated from that point onwards to default to a colour attribute of #000.
As an aside, assuming I perform this update, since the defaults is passed by reference, all existing boxes will also have their defaults updated. Is this correct?
var Box = Backbone.Model.extend({
defaults: {
"Colour" : "#FFF"
}
});
How can I update the defaults object of a Model?
For example, let's say I have Box object modelled below. It has a default "Colour" attribute set to "#FFF".
Once the user starts interacting with the server, at some point the server passes back a new default colour #000. I want all new boxes instantiated from that point onwards to default to a colour attribute of #000.
As an aside, assuming I perform this update, since the defaults is passed by reference, all existing boxes will also have their defaults updated. Is this correct?
var Box = Backbone.Model.extend({
defaults: {
"Colour" : "#FFF"
}
});
Share
Improve this question
asked Jul 7, 2011 at 3:53
fortuneRicefortuneRice
4,20411 gold badges45 silver badges60 bronze badges
2 Answers
Reset to default 10The default can be changed easily with
Box.prototype.defaults.Colour = '#000'
And when you change this, the boxes that have already been created will have, deep in their prototype chain, a new value
myBox.__proto__.constructor.prototype.defaults.Colour === '#000'
but that won't matter and it won't change the value that es from myBox.get('Colour')
because the defaults get copied tomyBox.attributes
at instantiation. To change existing boxes, you'd have to use myBox.set({'Colour': '#000'})
or myBox.attributes.Colour = '#000'
.
(I hope I interpreted your question correctly)
It seems like your Colour attribute is not really a state of your model that is saved. It may be more appropriate to have it be a class property. So you might do this:
var Box = Backbone.Model.extend({
// Instance properties here.
}, {
colour: '#FFF'
});
and then if you need to use this property, you reference it as:
Box.colour
and if you need to change it, you need only do:
Box.colour = #000;
This approach may or may not be appropriate to your app as there could be a reason why it needs to be an instance property. But it seems like its a property of the class more than a class' instances.
本文标签: javascriptbackbonejs updating model defaultsStack Overflow
版权声明:本文标题:javascript - backbone.js updating model defaults - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741442695a2379011.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论