Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone.js - extend router with beforeRoute filter

I am trying to implement a before filter for my routes in Backbone.js. I found the following code here -

var MyRouter = Backbone.Router.extend({
    route: function(route, name, callback) {
        return Backbone.Router.prototype.route.call(this, route, name, function() {
            this.trigger.apply(this, ['beforeroute:' + name].concat(_.toArray(arguments)));
            callback.apply(this, arguments);
        });
    }
});

However, I am not sure what I need to do next. I'll need to define a function with the "before route" logic I want, but I don't understand how exactly it will be invoked.

like image 632
Mark Sherretta Avatar asked Apr 09 '26 22:04

Mark Sherretta


1 Answers

The overridden route function triggers an event named beforeroute:routename, then calls the original route function. So if you have a route like this:

var MyRouter = Backbone.Router.extend({
    routes: { 
        "": "home"
    },
    // ...
});

Then you would subscribe to the beforeroute event using:

var router = new MyRouter()

router.on("beforeroute:home", function() {

    // before route logic here...
    alert("Home route is about to get hit ...");
});

Fiddle demo.

like image 127
McGarnagle Avatar answered Apr 12 '26 06:04

McGarnagle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!