Backbone.js model property constants - is this goo

2019-08-20 19:36发布

问题:

I have trouble keeping track of the properties of a Model instance. For example I have declarations such as:

MyModel = Backbone.Model.extend({});

Then in my views, I'm often doing something like:

var someVal = this.model.get('someProperty');

I was beginning the task of moving a View's strings into constants by encapsulating them in an object and passing it as a second parameter to a View's constructor, for example:

SchemaOptionsView = Backbone.View.extend(
    { /* Body of View here as usual */}, 
    {
        TEMPLATE: '#View-Template',
        INPUT_REQUIRED:'required'
    });

When I got to thinking, I could solve two problems by doing this with my Models:

MyModel = Backbone.Model.extend(
{ /* Body of Model here as usual */},
{
    PROPERTY_1 = 'p1',
    PROPERTY_2 = 'p2'
});

I could then use the constant to retrieve the property value:

var someVal = this.model.get(MyModel.PROPERTY_1);

This would allow me to clearly see the properties a Model instance contains, and also moves a string value into a constant in an appropriate place.

I have not seen this recommended or in any examples. Have I missed something? What do people think about this idea?

回答1:

This is solving a non problem. Your models should have well defined attributes - we use the defaults hash to enumerate all the available attributes of our models. Not only does this provide a catalog of the attributes that a model possesses but it also provides a way to override a non-validated input.



标签: backbone.js