Backbone router events

12,176

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
                }
        });
Share:
12,176
abuduba
Author by

abuduba

Updated on June 04, 2022

Comments

  • abuduba
    abuduba almost 2 years

    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?

  • KTastrophy
    KTastrophy almost 12 years
    Just a heads up, the "all" event is (in all cases I've seen triggered) last. So, in the case of routes it would work more like an after event.
  • drogon
    drogon over 10 years
    backbone version 1.0 has the "route" event now
  • Danny
    Danny over 10 years
    "route" event does not fire until after