Mr.M Mr.M - 1 month ago 13
Javascript Question

Backbone.js collection doesn't listen model change event

I've just started using backbone.js to create a spa. I'm trying to make a books collection listen to model change but nothing happens. This is the model and collection:

var Book = Backbone.Model.extend({

idAttribute: 'id',

defaults: {
id: null,
title: '',
author: '',
completed: false
}

});

var BooksCollection = Backbone.Collection.extend({

model: Book,

url: 'books',

initialize: function() {
this.listenTo(this.model, 'change', this.debug);
},

debug: function () {
console.log('something happened !!!');
}

});


This is the view:

var BookView = Backbone.View.extend({

template: _.template($('#viewBook').html()),

events: {
"click #save": "bookSave"
},

initialize: function() {
this.listenTo(this.model, 'change', this.render);
},

render: function() {
$(this.el).html(this.template(this.model.toJSON()));
return this;
},

bookSave: function() {
this.model.set({author: "nobody"});
}

});


When i click on the #save button the author is changed but nothing is logged. Where am i wrong ? Thanks.

Answer

Events from models automatically bubbles up to the collection, so you can listen to model changes directly like this:

// in the collection
initialize: function() {
    this.listenTo(this, 'change', this.debug);
},
Comments