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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With