priortd
priortd

Reputation: 49

Backbone routing not firing first time

I have started learning Backbone.js. I have set up a simple router for 3 links. 2 of them fire routing perfectly but one - the one with href="#/active" in the code below, will not fire the routing until I have clicked one of the other 2 links first.

Html is: <ul id = filters> <li> <a class="selected" href="#/">All</a> </li> <li> <a href="#/active">Active</a> </li> <li> <a href="#/completed">Completed</a> </li> </ul>

Javascript:

var Workspace = Backbone.Router.extend({

    routes: {
        '*filter': 'setFilter'
    },

    initialize: function() {
        this.on('route:setFilter', this.setFilt);
    },

    setFilt: function(param) {
        app.TodoFilter = param || '';
        app.Todos.trigger('filter');
    }
});
app.TodoRouter = new Workspace();
Backbone.history.start();

Upvotes: 0

Views: 87

Answers (2)

priortd
priortd

Reputation: 49

Thanks all, The routing I am using uses a splat to declares a default route that contains one parameter - the parameter name is filter and this gets passed as the param parameter in the setFilt(param). I've discovered that the problem is not with my routing as such. When I load the app first, all routes work fine. The problem is when I refresh the page wile I am on one route e.g with url http://localhost:5000/todo.html#/active. The setFilt functions is getting called before the page is fully rendered. Then when I click the Active link again, Backbone sees I am already on the correct route so setFilt function is not triggered. I need to look more into how to fix this but it is a tutorial that I am doing so I will move on for the moment. Thanks for your help though..

Upvotes: 0

rcarvalho
rcarvalho

Reputation: 790

Routers don't work like that, try this way.

routes: {

    'filter': 'setFilter',

    'active': 'activeRoter',

    'completed':'completedRouter'
},

 setFilter: function(){
    //Do something
  },

 activeRoter: function(){
   //Do something
  },
 completedRouter: function(){
   //Do something
  }

Upvotes: 1

Related Questions