Backbone.js:添加未触发集合的事件

发布于 2024-12-15 14:08:15 字数 686 浏览 1 评论 0原文

我有一个像这样定义的标准 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

泪冰清 2024-12-22 14:08:15

您的代码中有一些可疑的地方;您的 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 use collection.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 defining Observations, it seems you should try something similar.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文