我有一个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; ...糟糕!

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

因此,当您包装它时它起作用的原因更加有趣:
var wrapped = function() { this.bCollection.fetch(); };
this.fModel.on('change', wrapped, this);

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

因此,这是TL; DR:

您实际上想要:
this.fModel.on('change', this.bCollection.fetch, this.bCollection);

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

有道理?

干杯:)

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

10-12 12:54
查看更多