2014-02-19 72 views
0

我創建了一個視圖,它正在收聽一個集合。這個集合的模型被一次全部替換。我希望儘可能少地呈現視圖。Backbone:我應該聽什麼事件

查看:

BoxContent = Backbone.View.extend({ 

    initialize: function(options) { 
     console.log("BoxContent initializing"); 
     this.el = options.el; 
     this.collection = options.collection; 
     this.collection.on("add", this.update, this); 
     this.collection.on("reset", this.update, this); 
    }, 

    update: function(){ 
     this.render(); 
    }, 

    render: function() { 
     document.getElementById('boxContentHeader').innerHTML = localStorage.activeBox; 
     console.log("BoxContent rendering"); 
     var temp = _.template(maincontemp,{boxFolder: this.collection}); 
     this.$el.empty(); 
     this.$el.append(temp); 
     this.$el.trigger("create"); 
    }, 

    reset: function() 
    { 
     this.render(); 
    }, 

    close: function(){ 
     //console.log("off-logging clickListener"); 
     //this.collection.off(); 
     //$(this.el).off(); 
    } 
}); 

要更新我創建模型的一個數組集合,重新集合,並把新的數組集合。我需要傾聽重置,以使空集合呈現。 我不從平安服務器獲取數據。

是否有其他方法來收聽集合的更改?

編輯:

一個問題:雖然我只是添加的車型之一陣列收集,是骨幹呼籲每個模型的add事件這個數組裏面?

回答

2

查看文檔中的Catalog of Events。您可以聽取所有參數爲collection的事件。

  • add - (model, collection, options) - 將模型添加到集合時。
  • remove - (model, collection, options) - 將模型從集合中刪除時。
  • reset - (collection, options) - 集合的全部內容已被替換。
  • sort - (collection, options) - 收集已重新排序時。
  • destroy - (model, collection, options) - 模型被破壞時。
  • request - (model_or_collection, xhr, options) - 模型或集合開始向服務器發出請求時。
  • sync - (model_or_collection, resp, options) - 當模型或集合已被成功與服務器同步時。
  • error - (model_or_collection, resp, options) - 模型或集合對遠程服務器的請求失敗時。
  • all - 此特殊事件觸發任何觸發事件,將事件名稱作爲第一個參數傳遞。
+0

是常見的車型陣列添加到收藏? 或按模型添加模型會更好嗎? – marcel

+0

兩者都很好,這是來自'collection.reset'的官方文檔:*每次添加和刪除一個模型都很好,但是有時候您有太多的模型需要更改,您寧願更新收集散裝* – msvalkon

+1

謝謝,所以我繼續我的陣列。 – marcel

相關問題