【问题标题】:Why aren't my Backbone Route Events working?为什么我的主干路由事件不起作用?
【发布时间】:2014-10-31 14:29:53
【问题描述】:

有人可以解释为什么router.on("route:myTest", function(page) {}); 不起作用吗?

我的Backbone.Router如下:

var MyRouter = Backbone.Router.extend({
    initialize: function(){
        Backbone.history.start({ pushState:true, root:"/subdir/" });
    },
    routes: {
        '' : 'start',
        'base' : 'myTest',
        'base/:name': 'myTest',
        'base/:name/:skill': 'myTest',
        '*default': 'defaultRoute'
    },
    start: function(){
        alert('Chapter 5 route invoked');
    },
    defaultRoute: function(){
        alert('Router does not handle this route');
    },
    myTest: function(name,book){
        if(name !== undefined){
            if(book !== undefined){
                alert([name, 'is reading', book].join(' '));
            }else{
                alert('Saying hello to ' + name);
            }
        }else{
            alert('Saying hello!');
        }
    }
});

这是我的html页面上的代码:

function showBook(name){
    console.log('Show book ' + name);
    router.navigate('book/' + name);
}
router.on("route:myTest", function(page) { showBook('TestBook'); });

【问题讨论】:

    标签: javascript backbone.js backbone-events backbone-routing


    【解决方案1】:

    Backbone.Router 不会仅触发路由名称的事件(在这种情况下为myTest)。如果您查看the docs,您可以看到路由器触发了route、route:[name] 事件,因此您应该改用以下内容:

    router.on('route:myTest', function(){});
    

    如果路由与 base、base/:name、base/:name/:skill 匹配,则将触发该事件,这可能是也可能不是您要查找的内容。

    【讨论】:

    • 感谢您的帮助。我确实使用了'route:myTest',我最初的帖子是一个错字。对不起,那是我的错。我更新了我的帖子以反映我的实际代码(在底部)
    猜你喜欢
    • 2014-06-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
    相关资源
    最近更新 更多