Backbone.js On Trigger回调绑定未按预期工作



我有一个骨干集合,每当另一个骨干模型(不属于该集合的一部分)发生变化时,它都需要提取。

当我这样写的时候:

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绑定到它被调用的对象上——这现在是正常的javascript内容。


所以,这里有一个TL;DR:

你实际上想要:

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

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

有道理吗?

干杯:)

最新更新