Backbone.js:添加未触发集合的事件
我有一个像这样定义的标准 Backbone.js 集合:
class Observation extends Backbone.Model
class Observations extends Backbone.Collection
model: Observation
然后,我在集合的重置事件的事件处理程序中绑定像这样的添加事件:
collectionReset: (collection) =>
@collection.bind 'add', @elementAdded
问题是该事件没有被触发。我已经设置了一个断点并遍历了代码,下面的行(backbone.js 0.5.3 的 627)阻止了 add 事件的触发:
_onModelEvent: function (ev, model, collection, options) {
if ((ev == 'add' || ev == 'remove') && collection != this) return;
具体来说是以下比较:
collection != this
集合参数不同于“这个”引用。
有其他人以前见过这种情况吗?或者他们可以指出我做错了什么吗?
I have a standard Backbone.js collection defined like this:
class Observation extends Backbone.Model
class Observations extends Backbone.Collection
model: Observation
I then bind the add event like this in an event handler for the collection's reset event:
collectionReset: (collection) =>
@collection.bind 'add', @elementAdded
The problem is that the event is not being fired. I have set a break point and walked through the code and it is the following line (627 of backbone.js 0.5.3) that is stopping the add event from firing:
_onModelEvent: function (ev, model, collection, options) {
if ((ev == 'add' || ev == 'remove') && collection != this) return;
And it is specifically the following comparison:
collection != this
The collection argument is different from the 'this' reference.
Has anyone else seen this happening before or can they point out what I am doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的代码中有一些可疑的地方;您的 collectionReset 方法采用
collection
参数,但看起来您尝试使用@collection
绑定它,这是不同的。如果您确实想对传递的参数“collection”调用bind,则需要使用collection.bind
,而不是@collection.bind
。我主要将事件从模型类(包括集合)绑定到视图,在这种情况下,您通常只需引用模型进行绑定,即调用
@model.bind 'add', someMethod
。从定义Observations
的代码来看,您似乎应该尝试类似的操作。There's a couple of suspicious things in your code; your collectionReset method takes a
collection
parameter, but then it looks like you try to bind it you use@collection
, which is something different. If you really want to call bind on the parameter "collection" being passed, you need to usecollection.bind
, not@collection.bind
.I mostly bind events from model classes (including Collections) to Views, and in that case, you normally just refer to the model for binding, i.e. calling
@model.bind 'add', someMethod
. From your code definingObservations
, it seems you should try something similar.