Backbone Collection

时间:2017-03-09 12:52:25

标签: javascript backbone.js

我有一个页面,我必须显示7个集合的总数。 如果在集合中创建了任何新项目,那么我的页面应显示更新的计数。我尝试如下

this.listenTo(XyzCollection, 'update', function() {
  self.lengthVariable = XyzCollection.length;
  self.render();
});

这种方法的问题是,如果任何集合的计数很大(比如说1000),那么渲染方法会被多次调用(并且总共有7个集合被调用)。

我也试过

this.listenTo(XyzCollection, 'update', function() {
    self.lengthVariable = XyzCollection.length;
    //self.render();
});

即。只是更新变量,但页面剂量没有刷新,在模板上我看到计数为0(我注释掉渲染)。

请建议实现方案的正确方法

示例初始化和呈现视图如下:

initialize: function() {
    xxx1Collection.refresh();
    xxx2Collection.refresh();
    xxx3Collection.refresh();
    xxx4Collection.refresh();
    xxx5Collection.refresh();
    xxx6Collection.refresh();
    xxx7Collection.refresh();

    var self = this;

    this.listenTo(xxx1Collection, 'update', function() {
        self.var1 = xxx1Collection.length;
        self.render();
    });

    this.listenTo(xxx2Collection, 'update', function() {
        self.var2 = xxx2Collection.length;
        self.render();
    });

    this.listenTo(xxx3Collection, 'update', function() {
        self.var3 = xxx3Collection.length;
        self.render();
    });

    this.listenTo(xxx4Collection, 'update', function() {
        self.var4 = xxx4Collection.length;
        self.render();
    });  

    this.listenTo(xxx5Collection, 'update', function() {
        self.var5 = xxx5Collection.length;
        self.render();
    });

    this.listenTo(xxx6Collection, 'update', function() {
        self.var6 = xxx6Collection.length;
        self.render();
    });

    this.listenTo(xxx7Collection, 'update', function() {
        self.var7 = xxx4Collection.length;
        self.render();
    });
},

render: function() {
    this.$el.html(this.template({
        count1: self.var1,
        count2: self.var2,
        count3: self.var3,
        count4: self.var4,
        count5: self.var5,
        count6: self.var6,
        count7: self.var7,
    }));

}

1 个答案:

答案 0 :(得分:0)

假设在视图中存在7个具有增量名称​​的集合的充分理由,则在集合更新时重新呈现的最简单方法如下:

initialize: function() {
    // make collections properties of the view
    this.xxx1Collection.refresh();
    this.xxx2Collection.refresh();
    /* ... */
    this.xxx7Collection.refresh();

    // create the event hash once, and reuse it.
    var events = { update: this.render };

    // there's no need to use `self` when using `this.listenTo`
    this.listenTo(this.xxx1Collection, events)
        .listenTo(this.xxx2Collection, events)
        /* ... */
        .listenTo(this.xxx7Collection, events);
},

render: function() {
    // just pass the length here instead.
    this.$el.html(this.template({
        count1: this.xxx1Collection.length,
        count2: this.xxx2Collection.length,
        /* ... */
        count7: this.xxx7Collection.length,
    }));
}

来自Catalog of Events

  

“更新” (collection, options) - 任意后触发的单个事件   已从集合中添加或删除了多个模型。