js collection不监听模型更改事件

Backbone.js collection doesn't listen model change event

本文关键字:事件 模型 监听 collection js      更新时间:2023-09-26

我刚刚开始使用backbone.js创建一个spa。我试着让藏书听模型变化,但什么都没发生。这是模型和集合:

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