In backbone I can use my models in different ways.
As I understand, a (Data) model is used to store data (possibly served from a RESTful web server) and a ViewModel is used to store information about a specific view (The views hidden/shown state for example).
Most of my knowledge is from this SO question.
After reading this article where the author says:
Render UI Upon Data Change, Not User Interaction
and
The flow is : User interaction -> data change -> view render.
For instance, if we are writing a play/pause toggle button in an audio player, the flow would be:
- The user hits ‘play’
- The model (data) state changes to ‘playing’
- The view renders in ‘playing’ mode
Following this pattern ensures that changes to the state triggered from other sources (such as fast forward, new playlist, network error, etc.) will toggle our button to do the right thing. In other words, we have a single source of truth: whenever our model changes we know we should render our button.
var PlayPauseButton = Backbone.View.extend({
tagName: 'li',
className: 'icon',
initialize: function(){
this.model.on('change:status', this.render, this);
},
render: function(){
this.$el.removeClass('icon-play').removeClass('icon-pause');
this.$el.addClass('icon-' + (this.isPlaying() ? 'pause' : 'play'));
},
events: {
'click': function(){
this.model.set('status', this.isPlaying() ? 'paused' : 'playing');
}
},
isPlaying: function(){
return this.model.get('status') === 'playing';
}
});
I started to wonder the advantages and disadvantages of using each one.
Assuming we only have one model per view (I know we could have more, but if we limit it to one). I can think of,
ViewModel pros:
- The ones mentioned in the article.
- Information about a view is saved in a model, preventing the view being cluttered.
- State information can be shared between views.
cons:
- Cannot call Backbone's save() method because this will cause the model to save incorrect data to the server (the views state for example).
- Cannot call Backbone's fetch() method easily because we might trample our views data.
(Data) Model pros:
- Use backbone's built in save, fetch etc.
- views can share data without worrying about view specific data being stored in them.
cons:
- Models can only be used for data
Am I correct in thinking this?
Should I have a model for my data and a model for my view?
How does this work with collections?
I know Backbone is very loose and there are no hard and fast rules. But, does anybody have any real world experience of using one or the other? Or possibly both?
Any help is appreciated.