在主干路由器中使用以下代码,是否可以确保当用户直接导航到 #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/