简体   繁体   English

骨干收集“添加”事件未触发

[英]Backbone Collection 'add' event not firing

I've got an event listener in my Collection which listens for the 'add' event, which only seems to fire when the sample data I add in my router is added, but not when I add more models in my view, the code for both is below: 我的收藏夹中有一个事件侦听器,用于侦听“添加”事件,该事件仅在添加到路由器中添加的示例数据时才触发,但在我的视图中添加更多模型时,不会触发两者都在下面:

Collection: 采集:

Application.Collection.extend({
  name: "todos/todos",
  initialize: function() {
    this.on("add", console.log("added"));
  },
  url: "/todo-application/todos"
});

Router (this fires an event): 路由器(触发事件):

collection = new Application.Collections["todos/todos"]();
var m = new Application.Model({
    title: 'Finish screencast',
    done: true
});
collection.add(m);

View (this doesn't fire an event): 查看(这不会触发事件):

Application.View.extend({
  name: "todos/index",
  events: {
    "submit form": function(event) {
        event.preventDefault();
        var attrs = this.serialize();
        this.collection.add(attrs);
        this.$('input[name=title]').val('');
    }
  }
});

The collection.add in the view definitely works, as the model is added to the collection and displayed on screen , yet the collection only gives me a console.log() on the initial pageload when the sample data is added... 视图中的collection.add确实可以正常工作,因为将模型添加到了集合中并显示在屏幕上 ,但是当添加示例数据时,集合仅在初始页面加载时为我提供了console.log()

EDIT: 编辑:

According to my Backbone Chrome extension the event is indeed firing, but for some reason this event binding isn't working, and I have tried using this.listenTo instead of .on . 根据我的Backbone Chrome扩展程序,确实确实触发了该事件,但是由于某种原因该事件绑定无法正常工作,因此我尝试使用this.listenTo而不是.on

当在对象上使用on函数时,您callback绑定到该对象上的event ,并且该callback必须是一个函数,如下所示:

this.on("add", function() { console.log("added"); });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM