Backbone.js model potential constants - is it good practice?
I am having trouble keeping track of the properties of a model instance. For example, I have declarations like:
MyModel = Backbone.Model.extend({});
Then, in my views, I often do something like:
var someVal = this.model.get('someProperty');
I started the task of moving View strings into constants by encapsulating them in an object and passing it as a second parameter to the view's constructor, for example:
SchemaOptionsView = Backbone.View.extend(
{ /* Body of View here as usual */},
{
TEMPLATE: '#View-Template',
INPUT_REQUIRED:'required'
});
When I thought, 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'
});
Then I could use a constant to get the property value:
var someVal = this.model.get(MyModel.PROPERTY_1);
This will allow me to clearly see the properties that the model instance contains, and also moves the string value into a constant at the appropriate location.
I have not seen this recommended or in any examples. Did I miss something? What do people think of this idea?
source to share
This is the solution to the problem. Your models must have well-defined attributes - we use the default hash hash to list all the available attributes of our models. This not only provides a catalog of the attributes that the model possesses, but also provides the ability to override unaudited input.
source to share