Reputation: 135
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?
Upvotes: 1
Views: 2003
Reputation: 17430
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);
},
Upvotes: 1