0

Two common scenarios when I am using backbone backbone:

Attribute is listed as default value, then set

modelExample_A: Backbone.Model.extend({
  defaults: {
    whatever: 'foo'
    something: 'blah'
  }
});

viewExample_A: Backbone.View.extend({
  //our view definition
});

var Example_A = new viewExample_A({
  model: new modelExample_A()
})
Example_A.set({
  'whatever': 'bar',
  'something': 'weeeeeee',
});

Attribute is not listed as a default value, then set

modelExample_A: Backbone.Model.extend({
});

viewExample_A: Backbone.View.extend({
  //our view definition
});

var Example_A = new viewExample_A({
  model: new modelExample_A()
})
Example_A.set({
  'whatever': 'bar',
  'something': 'weeeeeee',
});

Attribute is not listed as a default value, set on creation

modelExample_A: Backbone.Model.extend({
});

viewExample_A: Backbone.View.extend({
  //our view definition
});

var Example_A = new viewExample_A({
  model: new modelExample_A({
    'whatever': 'bar',
    'something': 'weeeeeee',
  })
})

But what about situations where I want to set a property of the model? I know this is generally discouraged, but sometimes in my code I like to make a not of a what model is the parent of the current model. This is something that almost certainly won't ever change, so there is no reason to put in the attribute for event listening/onChange purposes. Further, this is something without a default value (it can only get a value in context), so is it okay to just set it as a property of the model? Or will this cause problems down the line?

Setting a property instead of an attribute

modelExample_A: Backbone.Model.extend({
  defaults: {
    whatever: 'foo'
    something: 'blah'
  }
});

viewExample_A: Backbone.View.extend({
  //our view definition
});

var Example_A = new viewExample_A({
  model: new modelExample_A({
    'whatever': 'bar',
    'something': 'weeeeeee',
  })
})
Example_A.parentModel = parentModelExample;
AlexZ
  • 11,515
  • 3
  • 28
  • 42

1 Answers1

3

Used in moderation and with consideration, setting non-attribute properties on model instances is fine. Just be careful not to have this be data that can easily get into an inconsistent state, and if you are doing this a lot, that's a code smell. In that case, you may want to consider modeling some state as actual models with attributes, but just not persisting them (never call .save).

Peter Lyons
  • 142,938
  • 30
  • 279
  • 274
  • Ah, forgot about save. The reason I ask is because I have some functions that deep loop over the entirety of the attributes for sanitation purposes, and I'd rather not have it run into a referenced object and explode with confusion. – AlexZ Jul 23 '13 at 00:30