【问题标题】:Next callback in Backbone Router骨干路由器中的下一个回调
【发布时间】:2016-03-24 16:36:32
【问题描述】:

如果第一个处理程序不满足/捕获特定情况,是否可以导航到下一个路由处理程序?

您可以使用 next()method 在 Express (nodejs) 中实现。

假设您有这样的路由器配置:

routes: {
    '*path': 'onPath',
    '*notFound': 'onNotFound'
},

onPath: function(path, next){
    if(path == 'something'){
        console.log('ok');
    } else {
        next();
    }
},

onNotFound: function(){
    console.log('KO');
}

我知道我可以混合使用onPathonNotFound 方法,但我只想知道是否可行。谢谢!

【问题讨论】:

  • 为什么不定义一个明确的路由然后处理呢?据我所知,如果要实现该功能,您将不得不推出自己的解决方案。
  • 条件不满足时直接重定向到notFound路径怎么样?

标签: backbone.js marionette backbone-routing


【解决方案1】:

首先,我不确定您是否可以在路由器中拥有 2 个路径匹配器。路由器如何知道使用哪个?这是一个选项。去掉notFound路由,直接调用方法:

routes: {
    '*path': 'onPath'
},

onPath: function(path){
    if(path == 'something'){
        console.log('ok');
    } else {
        this.onNotFound(path);
    }
},

onNotFound: function(path){
    console.log('KO');
}

或者更简洁的方法:你可以抛出一个事件(如果可以的话,避免太多的应用级事件。这只是一个例子)

App.trigger("pathNotFound", path);

在您的代码中的其他地方(同样,可能不在应用级别),您将需要侦听此事件:

App.listenTo("pathNotFound", function(){
               console.log('KO');
});

这都是大致写的。当然,您需要根据您的应用对其进行调整。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多