I recently started learning backbone and was wondering what would be the best way of grouping model attributes in a backbone model? I am thinking of having a specialized view that will handle a subset of the model’s attributes.
For example, if I have a car model, and I want to group all the information about the engine, so that I can pass these attributes to a view maybe? Something like car.engine_info
Car = Backbone.Model.extend({
initialize: function() {
this.engine_info = this._set_engine_info();
}
_set_engine_info: function() {
return {displacement:this.get('displacement'), horsepower: this.get('horsepower')};
}
You should consider making multiple models, not return a separate set of data. That data won’t have the power of backbone behind it for event handling and updates. You are creating a new object that just has properties and values.
Instead make models for each component
A car has – An engine, features, etc.
Then mixin the feature set into a car model by overriding the constructor
Another options would be to create a car and create some decorator functions that add the features, but frankly I prefer the method listed. Now you can have separate components listen to their own changes
The true power behind all of this is to separate responsibility of a car’s overall feature set. A car shouldn’t have to worry about all of it’s parts. Let the engine worry about the engine and let the features worry about the features.