2012-09-05 188 views
0

我想使用collection.reset()並沒有得到我期待在UI中的結果。響應返回2個結果,如預期的那樣。當我檢查我的收藏時,它總是告訴我我有2個結果,這也是正確的。雙渲染視圖

但是,在我的html輸出中,它只是將2個新獲取的行附加到表中。

initialize: function() { 
_.bindAll(this,'buildRows','refreshTable'); 
    this.template = _.template(maintmpl); 
    this.collection = txnList; 
    this.collection.bind("all", this.buildRows, this); 
    this.collection.on("reset", this.refreshTable, this); 
    this.collection.fetch(); 
}, 

events: { 
    "click #btn" : "refreshTable" 
}, 
render: function() { 
    this.$el.append(this.template()); 
}, 

refreshTable: function() { 
    this.collection.reset(); 
    console.log(this.collection.length) 
    this.collection.fetch(); 
}, 

buildRows: function(){ 
    var mainview = this; 

    _(this.collection.models).each(function(model){ 
     mainview.appendRow(model); 
    }); 
}, 

appendRow: function(model,i) { 
    var row = txnRow(model); 
    $('tbody',this.el).append(row.render().el); 
} 

所以最初,我使這個:

ROW1
行2

但與觸發refreshTable只追加2個行表按鈕的每次點擊:

ROW1
排2
排1
排2
Row1
Row2

我在想什麼?

+0

爲什麼要調用'collection.reset()'來響應集合中的一個''reset''事件? –

+0

我一直在嘗試使用reset()和fetch()方法的各種不同方式。顯然這些事件以某種方式引發了對方,但我不確定他們發射的確切順序。無論如何,我的代碼已經變得有點混亂,我想我錯誤地複製/粘貼了它。我甚至沒有意識到這一點,我一直盯着這個代碼這麼久。 :) – gerald

回答

0

骨幹collection.reset()方法對視圖沒有影響。您將不得不手動重新渲染視圖和新數據。

你的渲染函數不斷追加元素。骨幹在調用渲染之前不會清除你的$ el,它會讓你覺得不舒服。

試着改變你的渲染功能的財產以後這樣

render: function() { 
    this.$el.html(this.template()); 
}, 
+0

這在這種情況下並沒有什麼不同,因爲該模板只是將

與空的相加。當我調用appendRow時,它呈現一個並將其附加到tbody。 – gerald

0

它看起來像你清空集合,但不刪除舊的HTML。也許在render()嘗試替換元素的內容而不是附加到它。