jdlm
jdlm

Reputation: 6644

Two-ways route functionality

When clicking a tab in my Backbone app the routes work as expected and render the appropriate view:

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);
}

What I'm wondering is how I can cause the same functionality when writing a matching URL in the address bar? E.g. mydomain.com/app.html#section/about causes the "About" tab to be highlighted. Maybe I'm overlooking something, and perhaps the above is madness and not best practice at all.

Attaching a mockup of the app:

enter image description here

Upvotes: 1

Views: 485

Answers (1)

jevakallio
jevakallio

Reputation: 35890

I'll assume your tab links look something like this:

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

You should not catch the click event of the navigation links, i.e. remove your switchView and the associated event binding. Instead you should let Backbone.history catch the hash change and trigger the route.

To implement the tab change behavior, you can then subscribe to the route event in your view. This will handle the tab changes triggered by your tab links, as well as other URL changes.

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');
    }
  }
});

//code sample not tested

Upvotes: 1

Related Questions