backbone.js updating model defaults
How can I update the defaults object 开发者_如何学Pythonof 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"
}
});
The 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 comes 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.
精彩评论