奇怪的问题绑定事件与骨干,“;这个“;没有更新

Strange issue binding events with backbone, "this" is not being updated

本文关键字:这个 更新 问题 绑定 事件      更新时间:2023-09-26

我在处理主干和绑定事件时遇到了一个奇怪的问题。我会看看我是否能清楚地解释它(这是一个裁剪的例子…)

在一个视图中,我在初始化方法中有以下代码

var MyView = Backbone.View.extend({
  initialize: function(options) {
    //[...]
    this.items = [];
    this.collection.on('reset', this.updateItems, this);
    this.fetched = false;
  },
  render: function() {
    if (!this.fetched) {
      this.collection.fetch();  // fetch the collection and fire updateItems
      return this;
    }
    this.$el = $('#my-element');
    this.$el.html(this.template(this.items));
  },
  updateItems: function() {
    this.fetched = true;
    this.loadItems();
    this.render();   // call render with the items array ready to be displayed
  }
}

这个想法是,我必须获取集合,处理项目(this.loadItems),然后设置this.$el

我面临的问题是,在updateItems中,我看不到在绑定(this.collection.on…)之后添加任何属性

看起来绑定是针对冻结版本的视图进行的。我尝试添加属性来测试它,但在updateItems内部(如果被集合重置事件触发,则在render内部)我看不到添加的属性。

我在获取集合之前解决了绑定集合的问题,如下所示:

  render: function() {
    if (!this.fetched) {
      this.collection.on('reset', this.updateItems, this);
      this.collection.fetch();
      return this;
    }

但这是一种奇怪的行为。似乎在绑定时,会生成"this"的副本,而不是引用。

我说得对吗?或者我做错了什么?

您应该在集合视图的初始化阶段执行绑定:

// View of collection
initialize: function() {
    this.model.bind('reset', this.updateItems);
}

现在,当完成对集合的提取时,将调用updateItems方法。当然,在执行此操作之前,您需要绑定模型和视图:

var list = new ListModel();
var listView = new ListView({model: list}); 
list.fetch();