1

Backbone アプリでタブをクリックすると、ルートが期待どおりに機能し、適切なビューがレンダリングされます。

switchView: function(event) {
    event.preventDefault();

    // Get clicked tab
    var target = $(event.currentTarget);

    // Tab is already selected - do nothing
    if (target.parent().hasClass('selected')) {
        return;
    }

    // First remove selected status on all tabs
    this.$el.find('li').removeClass('selected');

    // Then select the clicked tab
    target.parent().addClass('selected');

    // Switch to new view
    var fragment = target.attr('href').split('#');
    Backbone.history.navigate(fragment[1], true);
}

私が疑問に思っているのは、アドレスバーに一致する URL を書き込むときに、どうすれば同じ機能を引き起こすことができるのでしょうか? たとえばmydomain.com/app.html#section/about、「About」タブが強調表示されます。たぶん私は何かを見落としているのかもしれません。おそらく上記は狂気であり、ベストプラクティスではありません。

アプリのモックアップを添付する:

ここに画像の説明を入力

4

1 に答える 1

1

タブ リンクは次のようになっていると仮定します。

<ul>
  <li><a href="#section/home">Home</a></li>
  <li><a href="#section/products">Products</a></li>
</ul>

clickナビゲーション リンクのイベントをキャッチしないでください。つまりswitchView、関連付けられているイベント バインディングを削除してください。代わりにBackbone.history、ハッシュの変更をキャッチしてルートをトリガーする必要があります。

タブ変更動作を実装するにはroute、ビューでイベントをサブスクライブできます。これにより、タブ リンクによってトリガーされたタブの変更や、その他の URL の変更が処理されます。

var TabView = Backbone.View.extend({
  initialize: function() {
    this.listenTo(Backbone.history, 'route', this.onRouteChanged);
  },

  onRouteChanged: function() { 

    //get current url hash part
    var hash = Backbone.history.getHash();

    //find the link that has a matching href attribute
    var $activeTab = this.$("a[href=#'" + hash + "']");

    //if route matched one of the tabs, update tabs.
    if($activeTab.is("a")) {

      // First remove selected status on all tabs
      this.$('li.selected').removeClass('selected');

      // Then select the clicked tab
      $activeTab.parent().addClass('selected');
    }
  }
});

//コードサンプルはテストされていません

于 2013-02-27T11:59:34.597 に答える