2015-01-15 164 views
0

採集模型通常當收集(S)的設計圖,我會綁定collection到視圖,並註冊相關的事件的collection這樣的:渲染骨幹

var Book = Backbone.Model.extend({}); 

var BookList = Backbone.Collection.extend({ 
    model: Book, 
    url: "/books" 
}); 

var BookListItemView = Backbone.View.extend({ 
    mtemplate: _.template($('#tpl_book_item').html()), 
    render: function() { 
     this.$el = $(this.mtemplate(this.model.toJSON())); 
     return this; 
    } 
}); 
var BookListView = Backbone.View.extend({ 
    el: '#content', 
    initialize: function() { 
     this.listenTo(this.collection, 'add', this.render); 
     this.listenTo(this.collection, 'remove', this.render); 
    }, 
    render: function() { 
     this.$el.empty(); 
     this.collection.each(function (item) { 
      this.$el.append(new BookListItemView({model: item}).render().$el); 
     }, this); 
     return this; 
    } 
}); 


Use: 

    var books = new BookList(); 
    var bookListView = new BookListView({ 
     collection: books 
    }); 
    books.fetch(); 

它的工作如預期:渲染每本書都在模板中定義。但是,我發現頁面中存在一個小問題。

我不確定這是否是由重新渲染視圖造成的?如圖所示,當books.fetch完成時,它會將書籍添加到books的集合中,對於每個book項目,將觸發一個add事件,然後通過刪除存在的項目並迭代集合來重新呈現頁面。

這意味着一旦有10本書,將有1+2+3+4...+10循環的BookListView

我我看來,一旦add事件觸發的,我不應該刷新整個名單,但只是增加一個新的視圖到BookListView,但如何對remove事件,似乎骨幹不提供任何內部方法來獲得從模型來看,所以一旦模型被刪除,我就無法得到相關的視圖。

你如何處理這種訴訟?

回答

2

不要將您的add綁定到render函數。相反,請爲此創建一個專用的添加方法。

var Book, BookList, BookListItemView, BookListView; 

Book = Backbone.Model.extend({}); 

BookList = Backbone.Collection.extend({ 
    model: Book, 
    url: "/books" 
}); 

BookListItemView = Backbone.View.extend({ 
    mtemplate: _.template($("#tpl_book_item").html()), 
    initialize: function() { 
    this.model.on("remove", this.remove); 
    }, 
    render: function() { 
    this.$el = $(this.mtemplate(this.model.toJSON())); 
    return this; 
    } 
}); 

BookListView = Backbone.View.extend({ 
    el: "#content", 
    initialize: function() { 
    this.listenTo(this.collection, "add", this.addItem); 
    }, 
    render: function() { 
    this.$el.empty(); 
    this.collection.each((function(item) { 
     this.addItem(item); 
    }), this); 
    return this; 
    }, 
    addItem: function(item) { 
    this.$el.append(new BookListItemView({ 
     model: item 
    }).render().$el); 
    } 
}); 

讓模型自己的視圖處理自己的刪除事件。

+0

'讓模型自己的View處理自己的remove事件'+1,我從來沒有想過,謝謝。 – hguser

+0

謝謝。我沒有完全測試上面的代碼,你可能需要改變一些東西。 – Exinferis