2013-03-18 92 views
1

我已經開始使用Backbone.js,並試圖繞過路由到特定視圖。在我的HTML中,我有<a href="#project/1">標籤來呈現項目任務的視圖。Backbone路由器和視圖

查詢

當點擊該鏈接,它追加與idDOM任務,然而,在點擊第二個鏈接時,其附加以前下這一任務。我不確定其最佳做法是否$.empty查看然後調用show方法?

我的路由器的一個片段:

routes: { 
    'project/:id: 'showtasks' 
}, 

showtasks: function(id) { 
    Event.trigger('tasks:show', id); 
} 

摘錄任務

initialize: function() { 
    Event.on('tasks:show', this.show, this); 
}, 

show: function() { 
    var task = this.collection.get(id); 
    var taskView = new App.Views.Task({ model: task }); 
    this.$el.append(taskView.render().el); 
} 

收集

var tasks = new App.Collections.Tasks([ 
    { 
     id: 1, 
     title: 'First Task', 
     content: 'Lots of Content...' 
    }, 
    { 
     id: 2, 
     title: 'Second Task', 
     content: 'Lots of Content...' 
    }, 
    { 
     id: 3, 
     title: 'Third Task', 
     content: 'Lots of Content...' 
    } 
]); 

var tasksView = new App.Views.Tasks({ collection: tasks }); 
+0

你想要它做什麼(一次只顯示一個)?當觸發事件時調用'$ .empty'就可以了。你說這是你的'Collection'代碼,但它看起來好像是一個Backbone'View'(因爲'Collection'沒有關聯元素('el''))。代碼看起來是一個'TaskViewViewer'?我不知道'id'來自'show'功能的位置......可能只是沒有顯示出來? – WiredPrairie 2013-03-18 21:47:51

+0

對不起,是的,這是我的'收集意見'。我會用集合更新我的問題。最終,我想嵌套集合,所以多個項目與一個項目相關聯。 – ashley 2013-03-18 21:54:10

+0

您可以清空附加到其中的html的任何事件,或者您可以調用它。$ el.html(taskView.render( ).el)來代替當前的內容。 – Kalpers 2013-03-19 00:33:18

回答

2

用於骨幹視圖夫婦的良好設計模式的收藏:

  • 多次調用render方法不應有任何副作用。它應該正確渲染。

  • 當你在渲染中使用append時,你基本上是在渲染方法中設置視圖的流程,這應該基本上是視圖模板的責任。

所以我建議你應該使用這個>

this.$el.html(taskView.render().el); 

這完全正常工作,但是你會進入一個問題,如果你有子視圖。爲此read this - (basically this whole answer is a shameless ripoff of this article :P)

+1

+1鏈接到文章,謝謝。我認爲每次清空和附加DOM都會給它帶來一些開銷。 – ashley 2013-03-19 09:37:36