Backbone – Execute route function before subroute’s function

Having the following code in a backbone router, is it possible to make sure that when a user navigates to #test/map or #test/images directly, the function attached to the route #test is executed first?

The invokeTest function creates a parent view which has the container in which the subviews “map” and “images” are rendered. so i need to make sure that base-layout view has been rendered before jumping to render the subviews.

var Workspace = Backbone.Router.extend({
  routes: {
    "test":                 "invokeTest",    // #test
    "test/map":        "invokeTestMap",  // #test/map
    "test/images": "invokeTestImages"   // #test/images
  },

  invokeTest: function() {
    //render base-layout
    console.log("test function executed");
  },

  invokeTestMap: function() {
    //render map view using element created with the base layout template
    console.log("Map function executed");
  },
  invokeTestImages : function(){
  //render images view using element created with the base layout template
  console.log("images function executed");
  }

});

right now i only get the console log for the subviews, the root function is never called.

Answer

You can just do:

  invokeTest: function() {
    //render base-layout
    createBaseLayout();
    console.log("test function executed");
  },

  invokeTestMap: function() {
    createBaseLayout();
    //render map view using element created with the base layout template
    console.log("Map function executed");
  },
  invokeTestImages : function(){
    createBaseLayout();
    //render images view using element created with the base layout template
    console.log("images function executed");
  }

Or you can do it like

invokeTestMap: function() {
    this. invokeTest();
    //render map view using element created with the base layout template
    console.log("Map function executed");
  },

Simply put you need to put the logic to be reused in a function and call it.

If you have to do this in large scale, in the initialize of your router you can identify parent-child relationships using regex and update the child callback to a function that wraps parent callback as well. (Or you can go even deeper into the router – There seems to be plugins that attempts to tackle similar problem like backbone.subroute.

Leave a Reply

Your email address will not be published. Required fields are marked *