【问题标题】:How to define/use several routings using backbone and requirejs如何使用主干和 requirejs 定义/使用多个路由
【发布时间】:2012-06-19 16:31:29
【问题描述】:

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

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

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

为什么会出现这种行为?
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/routing **

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
    });

});

【问题讨论】:

    标签: backbone.js routing requirejs marionette backbone-routing


    【解决方案1】:

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

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

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

    【讨论】:

    • 感谢您的回答。事实上,如果我设置 '': 'index1' 而不是 '*defaults': 'index1' 它将起作用。再次感谢。
    • @DerickBailey stackoverflow.com/questions/20017210/… 你能帮帮我吗:)
    • @DerickBailey 实际上似乎与您所描述的相反:如果您使用某种包罗万象的路线,则需要 first 加载它为了其他更具体的路线工作。理想情况下,应该指定行为,以便我们可以以一种或另一种方式依赖它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-11
    • 1970-01-01
    相关资源
    最近更新 更多