Backbone.js collection 不监听模型更改事件

Backbone.js collection doesn't listen model change event

我刚刚开始使用 backbone.js 创建水疗中心。我正在尝试制作一本书 collection 以听取模型更改,但没有任何反应。这是模型 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 !!!');
  }

});

这是观点:

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"});
    }

});

当我单击 #save 按钮时,作者已更改但未记录任何内容。我哪里错了?

来自模型的事件会自动冒泡到集合中,因此您可以像这样直接收听模型更改:

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