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);
}

所以最初,我渲染这个:

第 1行 第 2

但是每次点击触发 refreshTable 的按钮只会在表中追加 2 行:

第1

第2行 第1行 第2行 第1

第2

我错过了什么?

4

2 回答 2

0

主干 collection.reset() 方法对视图没有影响。您必须手动使用新数据重新渲染视图。

您的渲染函数不断附加元素。Backbone 在调用 render 之前不会清除你的 $el ,它由你决定。

尝试将您的渲染功能更改为这样的东西

render: function() {
    this.$el.html( this.template() );
},
于 2012-09-05T22:20:45.850 回答
0

看起来您正在清空集合,但没有删除旧的 HTML。也许在 render() 尝试替换元素的内容而不是附加到它。

于 2012-09-05T22:22:40.693 回答