Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically adding routes to Backbone.Router?

Here is my application-router.js file where i'm creating Backbone.Router object with just only few routes:

var App = App || {};

App.Router =  Backbone.Router.extend({
    routes : {
        ''      : 'showDashboard', // Not shown
        '*other': 'showModalError'
    },
    defaultRoute : function(other) { $('#modal404').modal(); }
});

In main javascript file application.js i'd like to programmatically add routes. I've tried with route() function and it doesn't work, routes are not added. It works however passing an object to the "constructor", but that will override already defined routes:

// This works and overrides all defined routes in App.Router
var router = new App.Router({ routes : { '/test/me' : 'testRoute' } });

// This is not working
router.route(ExposeTranslation.get('customers.new.route'), 'newCustomer');
router.route('/test/me/again', 'testAgainRoute');

In fact console.log(App.Router) shows:

routes Object { /test/me="testRoute"}

I suppose i'm missing something i can't figure out, i'm beginning learning this little piece of powerful javascript.

like image 620
Polmonino Avatar asked Mar 07 '12 02:03

Polmonino


1 Answers

Your router.route calls are working, those calls aren't your problem. When you call route to add a new route, the new route goes at the end of the routing list. In particular, the routes that are added by your route calls go after '*other' and '*other' will match anything so your new routes will be effectively ignored.

Try removing your '*other' route from routes and adding it after your two route() calls:

routes : {
    ''      : 'showDashboard' // Not shown
},

router.route(ExposeTranslation.get('customers.new.route'), 'newCustomer');
router.route('/test/me/again', 'testAgainRoute');
router.route('*other', 'showModalError');

The routes aren't stored in App.Router object, they're stored inside Backbone.history:

route: function(route, name, callback) {
  // ...
  Backbone.history.route(route, _.bind(function(fragment) {
    //...
  }, this));
  return this;
},

That's why your console.log(App.Router) doesn't say anything helpful.

like image 196
mu is too short Avatar answered Oct 05 '22 04:10

mu is too short