appRouter在加载时不会被触发

时间:2018-04-22 14:04:37

标签: javascript backbone.js requirejs

我正在尝试为我的骨干应用程序设置路由器。但是,当我转到localhost:8888/extractorslocalhost:8888/extractors/new时。两个控制台消息都没有输出。怎么在路由器本身定义它?

require(['new-extractor-view', 'extractors-collection', 'backbone'], function (NewExtractorView, ExtractorsCollection) {
    'use strict';

    var extractorCollection = new ExtractorsCollection();

    new NewExtractorView({
        collection: extractorCollection
    });

    //
    // Initialize URL router
    //
    var AppRouter = Backbone.Router.extend({
        routes: {
            'extractors': 'extractorsRoute',
            'extractors/new': 'newExtractorRoute',
            '*actions': 'defaultRoute'
        }
    });

    var appRouter = new AppRouter;


    appRouter.on('route:extractorsRoute', function () {
        console.log('test1')
    });

    appRouter.on('route:newExtractorRoute', function () {
        console.log('test2')
    });


    Backbone.history.start();
});

2 个答案:

答案 0 :(得分:1)

如果您想使用网址而不使用# ,则应初始化历史记录,如:

Backbone.history.start({ pushState: true })

详细了解pushState选项。

答案 1 :(得分:0)

代码看起来不错,但我认为在创建新路由器时忘记了括号:

var appRouter = new AppRouter();

编辑:哦,我非常确定Backbone只会匹配localhost:8888/#extractors(带有前导标签),但不会localhost:8888/extractors here所述。