javascript - Backbone - 在子路由函数之前执行路由函数

标签 javascript backbone.js

在主干路由器中使用以下代码,是否可以确保当用户直接导航到 #test/map#test/images 时,附加到路由 #test 的函数首先执行?

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

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

});

现在我只获得 subview 的控制台日志,根函数从未被调用。

最佳答案

你可以这样做:

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

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

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

关于javascript - Backbone - 在子路由函数之前执行路由函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42981127/

相关文章:

javascript - url 中没有哈希值的回家路线...backbone.js?

javascript - Bundle.js 在命令之后没有创建 - Node

javascript - Protractor 无法从列表中获取输入文本

javascript - Nodejs : Run a js file on node server startup

javascript - 使用 Ajax 运行 PHP 查询,以模式返回数据

serialization - Newtonsoft 中的 TypeNameHandling 需要 $type 作为第一个属性?

javascript - 用于登录和注销功能的 Backbone.js 架构

javascript - React JS 添加本地字体

Javascript 字符串对象只读?

javascript - 让模型听嵌套模型和集合的最佳模式?