javascript - 触发回调绑定(bind)上的 Backbone.js 未按预期工作

标签 javascript backbone.js

我有一个 Backbone 集合,每当另一个 Backbone 模型(不是集合的一部分)发生变化时需要获取它。

当我这样写的时候:

this.fModel = new FooModel();
this.bCollection = new BarCollection();
this.fModel.on("change", this.bCollection.fetch, this)

触发更改事件时出现以下错误:

Uncaught TypeError: Object #<Object> has no method 'trigger'

但是,当我简单地包装 Collection 的 fetch 调用时,它会按预期工作:

this.fModel = new FooModel();
this.bCollection = new BarCollection();
this.testfunc = function(){
    this.bCollection.fetch();
}
this.fModel.on("change", this.testfunc, this)

为什么会这样?谢谢!

最佳答案

这是一个有趣的尝试和解释:)

所以当你像这样调用 on 时:

this.fModel.on('change', this.bCollection.fetch, this);

您正在将运行 fetch 的上下文设置为 this 是什么。在此代码中,this 只是您的顶级应用程序或类似应用程序。 fetch 对此无能为力!我们来看一下fetch的实现:

// Fetch the default set of models for this collection, resetting the
// collection when they arrive. If `add: true` is passed, appends the
// models to the collection instead of resetting.
fetch: function(options) {
  options = options ? _.clone(options) : {};
  if (options.parse === undefined) options.parse = true;
  var collection = this;
  var success = options.success;
  options.success = function(resp, status, xhr) {
    collection[options.add ? 'add' : 'reset'](collection.parse(resp, xhr), options);
    if (success) success(collection, resp);
  };
  options.error = Backbone.wrapError(options.error, collection, options);
  return (this.sync || Backbone.sync).call(this, 'read', this, options);
},

所以我们基本上弥补了 var collection = this;...糟糕!

我们已将 fetch 中的 collection 设置为您的顶级应用程序!


所以当你包装它时它起作用的原因更有趣:

var wrapped = function() { this.bCollection.fetch(); };
this.fModel.on('change', wrapped, this);

我们已经将 wrapped 的上下文设置为 this。这很好,因为 this.bCollection 正是我们想要的。但是当你在这里调用 bCollection 上的 fetch 时,它以正常方式进行,将其中的 this 绑定(bind)到它被调用的对象 -现在这是普通的 javascript 内容。


所以,这是一个 TL;DR:

你实际上想要:

this.fModel.on('change', this.bCollection.fetch, this.bCollection);

因为 fetch 函数调用的上下文应该是集合本身,而不是其他。

有道理吗?

干杯:)

关于javascript - 触发回调绑定(bind)上的 Backbone.js 未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9753964/

相关文章:

javascript - 使用 jquery 类后退格键不起作用

javascript - 如何将链接的颜色从黑色更改为红色,并在再次单击时返回黑色

javascript - 如何在我通过页面切换时切换每个元素

javascript - GreaseMonkey 脚本中的什么会导致 Firefox 崩溃?

javascript - 无法使用 Backbone.Marionette 访问模型属性

javascript - 为ajax构建一个数组?

javascript - backbone.js "order"属性像 TodoMVC 不递增

javascript - 为什么我的backbone.Collection只有一个元素? (使用 Require、TypeScript、Jasmine)

javascript - 如何在更新集合时更新模板的一部分?

django - 适合单页 Web 应用程序的后端?