简体   繁体   English

Backbone.js - 自定义集合事件

[英]Backbone.js - Custom collection events

I'm trying to implement custom collection events for view binding. 我正在尝试为视图绑定实现自定义集合事件。

In my view I want to do something like: 在我看来,我想做的事情如下:

this.collection.on('available', this.available);

And somehow trigger this in method within my collection. 并以某种方式在我的集合中的方法中触发它。

So say I have a method in my collection which sets a particular models attribute (available), how could I then trigger all views that are bound to this method? 所以说我在我的集​​合中有一个设置特定模型属性(可用)的方法,然后我怎么能触发绑定到这个方法的所有视图?

Is this possible, and able to pass the model in question to the view for updating. 这是否可行,并且能够将有问题的模型传递给视图以进行更新。

Thanks for any help in advance, much appreciated :) 在此先感谢您的任何帮助,非常感谢:)

It's very simple to add new events to Backbone. 向Backbone添加新事件非常简单。 You just need to call the trigger method on the object that you want to trigger the event on. 您只需要在要触发事件的对象上调用trigger方法。

For example, assuming you're in a method of the collection, and have a model (called model ): 例如,假设您在集合的方法中,并且有一个模型(称为model ):

this.trigger('available', model);

The code to bind to the available event would just be as you described in your question. 绑定到available事件的代码就像您在问题中描述的那样。

EDIT: These days Backbone provides a listenTo method that you should usually use when binding to collection events from your views. 编辑:这些天Backbone提供了一个listenTo方法,您通常应该在从视图绑定到集合事件时使用该方法。 Views will automatically unbind from this event when their remove function is called, which stops old views from continuing to receive collection events after they have been removed. 调用其删除函数时,视图将自动从此事件解除绑定,这将阻止旧视图在删除后继续接收集合事件。 From your view, this can be used like this: 从您的角度来看,这可以像这样使用:

this.listenTo(this.collection, 'available', this. available);

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

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