简体   繁体   English

骨干绑定以在集合上添加事件

[英]Backbone binding to add event on collection

I have problem with backbone collections. 我对主干集合有疑问。 I trying to listen all events on collection: 我试图听所有关于收藏的事件:

  this.collection.on('all', function(ev) {
    console.log(ev);
  });

And collection trigger event only when I create record like this: 并且只有当我创建这样的记录时,集合触发事件:

  this.collection.create({name: 'aloha'});

But not when I create model instance directly: 但是当我直接创建模型实例时不是:

  var room = new Room({name: 'hello'}); // this code not trigger any events on collection
  room.save();

I am new to Backbone, but I think that second code should trigger event. 我是Backbone的新手,但我认为第二个代码应该触发事件。 Can somebody help me? 有人可以帮我吗? Thanks! 谢谢!

The event is not triggered on the collection, because the room model is not associated (ie has not been added) to this.collection . 该事件不会在集合上触发,因为room模型未与this.collection关联(即尚未添加)。

Assuming you have defined your model and collection similar to: 假设您已经定义了modelcollection类似于:

var Room = Backbone.Model.extend();

var Rooms = Backbone.Collection.extend({
  model:Room
});

var rooms = new Rooms();

rooms.on('all',function(eventName) {
  console.log(eventName);
});

For your code to work as expected you would have to add the room model to the rooms collection such as: 为了使代码按预期工作,您必须add room模型addrooms集合中,例如:

var room = new Room({'name':'hello'});

// This will trigger the add event on the collection
rooms.add(room);

// save the model
room.save();

The following is short-hand for the above code block: 以下是上述代码块的简写:

var room = rooms.create({'name':'hello'});

Here is a FIDDLE showing the behavior. 这是显示行为的FIDDLE

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

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