2012-03-05 23 views
1

編輯:這個問題與this one非常相似,但它更「概念上」。理解backbone.js作爲一個整體

假設一個單頁的應用程序與靜態鏈接的反彈反映routes

<!-- Top navlist --> 
<ul class="nav nav-list"> 
    <li><a class="active" href="#/customers">Customers</a></li> 
</ul> 

<!-- Left navlist --> 
<ul class="nav nav-list"> 
    <li><a class="active" href="#/customers">Show customers</a></li> 
    <li><a href="#/customers/new">Create customer</a></li> 
</ul> 

我需要設置class="active"一個(或多個)基於當前路線上的鏈接。哪種方法是正確的?

  1. 創建LinkLinkCollection模型,只要LinkCollectionViewLinkView,從頭開始:這似乎矯枉過正給我。似乎沒用,因爲鏈接不依賴於服務器端(它們不是動態創建的)。
  2. 創建LinkLinkCollection模型迭代現有鏈接。
  3. 忘記模型,併爲每條路線手動設置class="active"。像$('body').find('a[href="#/customers"]').addClass('active')。似乎代碼重複給我。
  4. 創建一個「全局」AppView視圖並執行像pt。 3在render() funcion。

路由定義的例子:

<script> 
    (function($){ 
     var MyApp = { Models : {}, Collections : {}, Views : {} }; 

     // The Router 
     MyApp.Router = Backbone.Router.extend({ 
      routes : { 
       '/customers'  : 'showCustomersView', 
       '/customers/new' : 'showCreateCustomerView' 
      }, 
      showCustomersView  : function() { 
       // Make customers links active 
      }, 
      showCreateCustomerView : function() { 
       // Make new customer links active 
      }, 
     }); 

    })(jQuery); 
</script> 

回答

2

我不能向「最佳實踐」說話,但我相當肯定,涉及車型專爲代表內部應用鏈接的目的是,爲你說,絕對是過度殺傷,而不是他們的預期用途。

我個人會做類似於模式#4的事情。在一個項目中,我目前的工作,我有一個看起來有點像這樣的APPVIEW:

AppView = Backbone.View.extend({ 

    events: { 
    "click a.internal" : "handleLink" 
    }, 

    handleLink: function (event) { 
    var route = $(event.target).attr('data-route'); 
    router.navigate(route, true); 
    return false; 
    }, 

}); 

我不使用我的錨標籤的實際href屬性來指定目標路徑,因爲我使用pushState的。相反,我使用元素類internal來指示將用於我的應用程序內部導航的錨標記。然後我使用另一個任意元素屬性route來指示鏈接應該去的地方。

鏈接可能看起來像這樣的事情,那麼:

<a href="#" class="internal" data-route="projects/3">My Third Project</a>

添加的額外位以添加CSS類,你要那麼也只是做一個jQuery的/的Zepto調用的問題handleLink

同樣,我不一定相信這是一種常見的/最佳實踐,但至少對我的目的來說,它似乎是足夠簡單和直接的(並且也適用於pushState)。

編輯:爲了語法的有效性,使用steveax的建議data-route

+0

+1的解釋。但我認爲'router.navigate'將打破MVC模式背後的哲學。這是應該檢索數據並提供正確視圖的路由器。恕我直言,這就是它應該做的。 – gremo 2012-03-05 22:09:53

+0

可能更好地使用數據路由,這種有效的語法。 – steveax 2012-03-06 00:35:09

+0

好的呼叫,steveax。我更新了我的答案。 Gremo,我不確定你的意思。路由器*是*檢索數據並提供視圖 - 所有這些都是讓路由器響應鏈接點擊。查詢/查看邏輯仍然在路由器中,僅此而已。 – 2012-03-06 01:42:32

相關問題