简体   繁体   中英

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?

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

A more (new) Backbone way of writing the bind is:

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

a better listen would be just route if you ask me; Because all triggers two events, i think these:

"route:[name]" (params) — Fired by the router when a specific route is matched.
"route" (route, params) — Fired by the router when any route has been matched.

I am new to backbone. Following Laurens answer, I managed to call on each route change with below

app_router.on('route', function(e){
    console.log(e);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM