Backbone router events

abuduba picture abuduba · Jan 19, 2012 · Viewed 12.2k times · Source

Does in Backbone.Router exists the events both before and after performing routing? My app works with jQuery.mobile and call to $.mobile.changePage was needed before route was performed and in controller have access to currently showing page by $.activePage. When action of controller is done, I should trigger the create event on document to get 'enhanced' by $.mobile newly created elements. I did this by replacing loadUrl

Backbone.history.loadUrl = ( function( old  ){
    return function() {  
       Router.trigger("all:before");   
       old.apply( Backbone.history, arguments );
       Router.trigger("all:after" );
    }
})( Backbone.history.loadUrl  );



 //Router.initialize
 initialize: function() {
     this.bind( "all:before", function( ) {  
         $.mobile.changePage( window.location.hash.split( "/" )[0] || "home", { changeHash:false} );
     });

     this.bind( "all:after", function() {
       $.mobile.activePage.trigger('create'); 
     });  
  }

Is there maybe some built-in events like this?

Answer

Sander picture Sander · Jan 19, 2012

there is no before and after event in the Backbone.Router as of now.

version 0.5.3 supports the following router events (all events here)

"route:[name]" (router) — when one of a router's routes has matched.

not sure for which release it will be, but a general route event is being developed, in the github trunk commit #419 has this functionality, but it's not released in a new version yet

there are allready reported issues (idea's) for a before event, check the github issue on that here.

so, the before event is not yet in there, the after event will come some time later, if you really already need an after event, there is a way you can put it in yourself, by binding to the 'all' event instead, it catches all events including all 'route:routename' events. then just split the event name and if it starts with route you have the general route event. (this can of course be removed and changed if the after event is released in one of backbone's releases)

    this.bind('all', function (trigger, args) {
               var routeData = trigger.split(":");
                if (routeData[0] === "route") {
                   // do whatever here.  
                   // routeData[1] will have the route name
                }
        });