Backbone - 在子路由功能之前执行路由功能

时间:2017-03-23 15:58:47

标签: javascript backbone.js

在骨干路由器中使用以下代码,是否可以确保当用户直接导航到#test/map#test/images时,将执行附加到路由#test的功能第一λ

invokeTest函数创建一个父视图,其中包含渲染子视图“map”和“images”的容器。所以我需要确保在跳转渲染子视图之前已经渲染了基本布局视图。

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");
  }

});

现在我只获取子视图的控制台日志,从不调用root函数。

1 个答案:

答案 0 :(得分:1)

你可以这样做:

  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");
  }

或者你可以像

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

简单地说,您需要将逻辑放在函数中重用并调用它。

如果必须大规模地执行此操作,则在路由器的initialize中,您可以使用正则表达式识别父子关系,并将子回调更新​​为包装父回调的函数。 (或者你可以更深入地进入路由器 - 似乎有一些插件试图解决像backbone.subroute这样的类似问题。

相关问题