簡體   English   中英

骨干收集

[英]Backbone Collection

我有一個頁面必須顯示7個集合的總數。 而且,如果在集合中創建了任何新項目,則我的頁面應顯示更新的計數。 我嘗試如下

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

這種方法的問題是,如果任何集合的數量很大(例如1000),則render方法被調用了很多次(總共有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,
    }));

}

假設在視圖中存在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,
    }));
}

事件目錄

“更新” (collection, options) -在從集合中添加或刪除任何數量的模型后觸發的單個事件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM