0

如果我有一个视图,其中有一个在初始化函数中获取的集合,但视图需要在获取返回之前清理,我如何取消绑定成功和/或错误回调?

因此,使用这样的代码:

Backbone.View.extend({
  initialize: function () {
    this.collection = new MyColl();
    this.collection.fetch({
      success: this.successCallback,
      error: this.errorCallback
    });
  },
  close: function () {
    // what goes here to keep successCallback and errorCallback from being called?
  }
});

当我调用 myView.close() 来清理它(在这种情况下显示另一个视图),并且我不想稍后调用successCallback(在视图“清理”之后)。

我试过了:

close: function () {
  this.collection.unbind('reset');
}

但是该集合似乎在 fetch 后的 _callbacks 内部 var 中没有列出 this 事件,因此 unbind 似乎没有帮助。

4

1 回答 1

1

你总是可以在 this.successCallback 和 this.errorCallback 中添加一个逻辑标志来检查 this.close 是否被调用:

Backbone.View.extend({
  initialize: function () {
    this.collection = new MyColl();
    this.collection.fetch({
      success: this.successCallback,
      error: this.errorCallback
    });
  },
  close: function () {
     // do stuff
     this.closed = true;
  },
  successCallback: function() {
    if(this.closed) return;
    //Do stuff
  }
});

或者,您不应该真的以这种方式设置您的事件。如果您改为执行以下类似操作,则更加“骨干”:

Backbone.View.extend({
  initialize: function () {
    this.collection = new MyColl();
    this.collection.bind('reset', this.SuccessCallback);
    this.collection.bind('error', this.errorCallback);
  },
  close: function () {
     // do stuff
     this.collection.unbind('reset', this.successCallback);
     this.collection.unbind('error', this.errorCallback);
  },
  successCallback: function() {
    //Do stuff
  }
});
于 2012-02-09T00:07:13.960 回答