2011-12-23 50 views
2

我有一個項目的集合,他們都共享一些數據(如ID,標題),但在他們共享的屬性幹,他們是功能獨特的項目,並有單獨的意見和業務邏輯。在Backbone.js混合收藏集的最佳設計模式

我的問題是沒有在骨幹風格的MVC的經驗,我不知道每個優點/缺點...或者如果有一個更優雅的解決方案,我錯過了。以下是我可能使用的3種技術的示例?

var gizmoCollection = new Backbone.Collection(); // or extend 
var gizmoModel = Backbone.Model.extend({ ... }); 

var morgView = Backbone.View.extend({ ... }); 
var blarView = Backbone.View.extend({ ... }); 


// 1.) Create an attribute for the view in the model? 
gizmoCollection.add(new gizmoModel({ title: 'Gizmo1': view: morgView })); 
gizmoCollection.add(new gizmoModel({ title: 'Gizmo2': view: blarView })); 


// 2.) Or create a seperate model for each type of model? 
var morgModel = morgModel.extend({}); 
var blarModel = blarModel.extend({}); 

gizmoCollection.add(new morgModel({ title: 'Gizmo1' }); 
gizmoCollection.add(new blarModel({ title: 'Gizmo2' }); 


// 3. Or register 'types' of views? 
gizmoView.subClassView('morg', morgView); 
gizmoView.subClassView('blar', blarView); 
gizmoCollection.add(new gizmoModel({ title: 'Gizmo1', type: 'morg' }); 
gizmoCollection.add(new gizmoModel({ title: 'Gizmo2', type: 'blar' }); 

回答

1

我的選擇是創建單獨的模型,並在必要時進行查看。原因是每個模型都應該爲自己保留業務邏輯。現在,如果只有表示邏輯對每個模型類型或模型屬性值都有所不同,您可能會發現僅通過子視圖就可以做到這一點。

你應該記住以下幾點:

  1. 表象邏輯進入演示(S)(Backbone.View)
  2. 業務邏輯裏去模型(S)(Backbone.Model)
  3. 導航邏輯路由器(又名控制器),或者你可以從Backbone.Events或jQuery.callbacks()做你的事件總線,它可以完成這項工作,並可能與你的演示者和模型分開。

最後說明。請始終記住,您的應用程序將會增長,有時候增加更多的代碼行更明智,無論您目前不需要那麼複雜。但是,如果你的感覺告訴你,在某些時候代碼會變得更復雜,那麼你應該馬上做,否則你就沒有足夠的時間。