简体   繁体   English

骨干路由器添加路由作为功能

[英]backbone router add route as function

I am using Backbone.js and I have a router.我正在使用 Backbone.js 并且我有一个路由器。 this is my routes property of the router:这是我的路由器的路由属性:

routes: {
    "pagea": "pageafunc",
    "pageb": "pagebfunc",
    "pagec": "pagecfunc",
}

is it possible to add a route that looks like this:是否可以添加如下所示的路线:

"mypath/*subroute": function(subroute) {
    //do somethong  
}

? ?

Nope, the routes object can only have string values.不, routes对象只能有字符串值。

If you want to pass your own callback, you need to set up the route programatically.如果要传递自己的回调,则需要以编程方式设置路由。 For instance, in your router's initialize function, you can do this:例如,在路由器的初始化函数中,您可以这样做:

this.route('mypath/*subroute', 'mypath_subroute', function(){
  // Route callback stuff.
});

That said, this can get very unreadable quickly, and it means that you have to scan through your initialize functions to know all of the routes you have defined, so storing all of the routes in the routes object is much cleaner.也就是说,这会很快变得非常不可读,这意味着您必须扫描初始化函数以了解您定义的所有路由,因此将所有路由存储在routes对象中会更清晰。 Or at least keep the route function body on the Router itself and keep the route paths in a separate section for readability.或者至少将路由函数体保留在路由器本身上,并将路由路径保存在单独的部分中以提高可读性。

The accepted answer is incorrect, or possibly just outdated.接受的答案不正确,或者可能只是过时了。 In either case, per the official Backbone docs :无论哪种情况,根据官方Backbone 文档

The routes hash maps URLs... to functions on your router ( or just direct function definitions, if you prefer )路由散列将 URL... 映射到路由器上的函数或者只是直接函数定义,如果您愿意

Wahoo!哇! That means you should be able to do something like:这意味着您应该能够执行以下操作:

var
Router= Backbone.router.extend({
  routes:{
    "path/to/:view": function(view){ console.log(view); }
    }
  });

It's a handy shorthand if, for example, you'll want to extend modify the {routes} object before initial instantiation or somesuch.例如,如果您想在初始实例化之前扩展修改{routes}对象或类似内容,那么这是一个方便的简写。 However, it's worth noting that using an anonymous callback will disable namespaced events from triggering for that route.但是,值得注意的是,使用匿名回调将禁止为该路由触发命名空间事件。 (See @loganfsmyth's comment above.) Still, this probably isn't the worst trade-off, depending on your use-case. (请参阅上面@loganfsmyth 的评论。)不过,这可能不是最糟糕的权衡,具体取决于您的用例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM