7

我将我的应用程序分成几个应用程序。

main.js
app.js
app1/
  |- routing
  |- controller
  |- app
app2/
  |- routing
  |- controller
  |- app

1)当我尝试使用路由器时app1,它们可以工作。
2) 当我尝试在 中使用路由器时app2,它们不起作用。3)如果我在工作中的路由器中
注释该行。'js/app1/routing',main.jsapp2

为什么我会得到这种行为?
在 github 上是否有一些使用多个路由和 requirejs 的应用程序示例?

谢谢。

这是我的代码:


** main.js **

define([
    'js/app',
    'js/app1/routing', // the routers in this app work
    'js/app2/routing'  // the routers in this app do not work but 
                       // if I comment the previous line (js/app1/routing',) 
                       // they works
],
function (App)
{
    "use strict";
    App.initialize();
});

** app.js **

define([],
function ()
{
    "use strict";
    var app = new Backbone.Marionette.Application();

    return app;
});

** app1/路由 **

define(['backbone','app1/controller'], function(Backbone, controller)
{
    "use strict";
    var Router = Backbone.Marionette.AppRouter.extend({

        appRoutes: {
            '*defaults': 'index1'
        }

    });
    return new Router({
        controller: controller
    });

});

** app2/routing.js **

define(['backbone','app2/controller'], function(Backbone, controller)
{
    "use strict";
    var Router = Backbone.Marionette.AppRouter.extend({

        appRoutes: {
            'app2': 'index2'
        }

    });
    return new Router({
        controller: controller
    });

});
4

1 回答 1

5

该问题可能是由加载路由器文件和创建路由器的顺序引起的。

Backbone 的history对象负责执行路由。当路由器被实例化时,它收集所有路由器上定义的所有路由。然后它会监视浏览器的 url 是否有变化。当它看到更改时,它将采用第一个可用的匹配路由并触发该路由,跳过其他任何内容。

当您*defaults定义了路线时,一切都与此匹配。因此,如果先加载此路由,则不会命中其他任何内容。因此,您需要在路由参数中更加明确,以使这条路由不会一直命中,或者您需要确保最后加载此路由器。

于 2012-06-17T18:08:03.640 回答