Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute a function before changing route in Backbone.js

How can I get notified before a Backbone router call the specific routing function?

I'd like to have a generic "reset" function before rendering every page.

Is there any event I can bind?

Update: the solutions I found are based on extending the router or the history in order to trigger the event.

like image 501
Ghigo Avatar asked Feb 02 '23 07:02

Ghigo


2 Answers

It looks like the 1.1.x release of Backbone has what you want with the Router.execute method:

MyRouter = Backbone.Router.extend({
  routes: {},

  // fired before every route. 
  execute: function(callback, args) {
    // ...
  }
});
like image 89
zedd45 Avatar answered Feb 15 '23 12:02

zedd45


if execute function is present it will be called before every route change but you must pass the arguments in callback to properly execute other matching routes.

MyRouter = Backbone.Router.extend({
      routes: {},

      // fired before every route. 
      execute: function(callback, args, name) {
         //your logic
         if (callback) callback.apply(this, args); //this must be called to pass to next route
       },
    });
like image 43
Suben Saha Avatar answered Feb 15 '23 14:02

Suben Saha