double rendering view

2019-09-04 07:35发布

问题:

I'm trying to use the collection.reset() and am not getting the results i am expecting in the UI. The response returns 2 results, which is as expected. When i inspect my collection, it always tells me i have 2 results, which also is correct.

However, in my html output, it just keeps appending the 2 newly fetch rows to the table.

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

so initially, i render this:

Row1
Row2

But with every click of the button that triggers refreshTable just appends 2 more rows to the table:

Row1
Row2
Row1
Row2
Row1
Row2

What am i missing?

回答1:

It looks like you're emptying the collection, but not removing the old HTML. Maybe in render() try replacing the element's content rather than appending to it.



回答2:

The backbone collection.reset() method has no effect on views. You will have to re render the view with the new data manually.

Your render function keeps appending elements. Backbone wont clear your $el before calling render, it leaves that upto you.

try changing your render function to somthing like this

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


标签: backbone.js