Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone.js trigger function each time Router is used

Just wondering if there is a simple way to trigger a custom function each time a Backbone.js router is utilized, without having to add it in each of the router functions. Now my script looks like this:

var AppRouter = Backbone.Router.extend({

    routes: {
        '' : 'index',
        'test': 'test',
    },

    initialize: function() {
    },

    index: function() {
        customFunction();
        indexView.render();
    },

    test: function() {
        customFunction();
        testView.render();
    },

});

I would like to have it something like this:

var AppRouter = Backbone.Router.extend({

    routes: {
        '' : 'index',
        'test': 'test',
    },

    initialize: function() {
    },

    index: function() {
        indexView.render();
    },

    test: function() {
        testView.render();
    },

    change: function() { 
        customFunction();
    }

});

Does anyone have any suggestions?

like image 685
hampusohlsson Avatar asked Mar 14 '12 14:03

hampusohlsson


1 Answers

Whenever a route is matched by the Router, a route:[name] event is fired with the name of the route matched, to allow classes to listen to certain route matches. All backbone objects also support the all event which fires whenever an event does.

So you could make use of this to bind to the all event on the Router, which will fire whenever the router does some routing.

initialize: function() {
    this.bind( "all", this.change )
},

If you were interested in the route that matched, it is passed as the first parameter to the bound function.

More details here in the FAQ

like image 117
obmarg Avatar answered Sep 23 '22 20:09

obmarg