Backbone.js触发器回调绑定不能按预期工作

时间:2012-03-17 21:37:48

标签: javascript backbone.js

我有一个Backbone Collection,只要另一个Backbone Model(不是Collection的一部分)发生变化就需要获取。

当我这样写时:

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)

为什么会这样?谢谢!

1 个答案:

答案 0 :(得分:6)

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

所以当你像这样打电话给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; ... 哎呀!

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


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

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

我们已将wrapped的上下文设置为this。那很好,因为this.bCollection正是我们想要的。但是当你在这里fetch上调用bCollection时,它正在以正常方式进行,将this内部绑定到它所调用的对象 - 这是正常的javascript内容。


所以,这是TL; DR:

你真的想要:

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

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

有意义吗?

干杯:)