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
Add a ment  | 

2 Answers 2

Reset to default 10

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