I'm new in Backbone. Here is my question. I have a collection of song list and an index of current play song of this list in collection. The code is like :
var songCollection = Backbone.Collection.extend({
initialize: function(){
...
this.index = 0;
...
},
...
getNextSong:function(){
...
this.index++;
...
}
})
And there is a view to show the content of the current playing song. I want to update the view info when the current playing song changes.Below code doesn't work in view.
var view = Backbone.View.extend({
initialize:function(options){
this.options.on('change:index', this.render, this);
}
)}
Nor does
this.listenTo(...);
Could someone tell an approach to solve this?
"change:[attribute]" (model, value, options) — when a specific attribute has been updated - Events-catalog
Change events are triggered for changes inside models attributes
hash, Changing random properties of a collection won't fire any events as far as I know.
You should better have a flag like isPlaying
in the model's attributes, and listenTo it's change on collection from the view.
var songModel = Backbone.Model.extend({
defaults: {
isPlaying: false
}
});
var songCollection = Backbone.Collection.extend({
model: songModel
});
var view = Backbone.View.extend({
initialize: function(options) {
this.listenTo(this.collection, 'change:isPlaying', this.render);
},
render: function(model, value, options) {
if(value){
//---------------^ this is the playing song, render it
}
}
});