1

我使用 EmberJS v1.0.0-rc.2 和 requireJS。
我的应用程序结构有点像这样。

- app
- - moduleA

我的主文件:

#app/main.js

var App = Ember.Application.create({
    VERSION: '1.0',
    //Log router transitions:
    LOG_TRANSITIONS: true
});

App.Router.map(function() {
    AppRouting.call(this);
});

App = AppRoutingExtend(App);

App.initialize();

函数 AppRouting() 和 AppRoutingExtend() 可以在同伴文件中找到:

#app/routing.js

function AppRouting() {
    this.resource('root', {path: '/'}, function() {
        this.resource('moduleA', {path: '/'}, function() {
            ModuleARouting.call(this);
        });
    });
}

function AppRoutingExtend(App) {
    var ModuleARouting = ModuleARoutingExtend();

    //Check if ModuleARouting is not empty
    if (!Ember.isEmpty(ModuleARouting)) {
        $.each(ModuleARouting, function(key, value) {
            //Check if key is a string of only letters 
            //  And if value is like Ember.Route.extend({})
            if (typeof key === 'string' && /^[a-zA-Z]+$/.test(key)
                && value.toString() == '(subclass of Ember.Route)') {
                eval("App.Root" + "ModuleA" + key + "Route = value");
            } else {
                //Throw error
            }
        });
    }

    return App;
}

函数 ModuleARouting() 和 ModuleARoutingExtend() 可以在以下文件中找到:

#app/moduleA/routing.js

function ModuleARouting() {
    this.route("contributors", {path: "/"});
    this.resource('aContributor', {path: "/:githubUserName"}, function() {
        this.route("details", {path: "/"});
        this.route("repos", {path: "/repos"});
    });
}

function ModuleARoutingExtend() {
    var routes = {};

    routes['Contributors'] = Ember.Route.extend({
        /*
            Some Code
        */
    });
    routes['AContributor'] = Ember.Route.extend({
        /*
            Some Code
        */
    });
    routes['AContributorDetails'] = Ember.Route.extend({
        /*
            Some Code
        */
    });
    routes['AContributorRepos'] = Ember.Route.extend({
        /*
            Some Code
        */
    });

    return routes;
}

我创建AppRouting()ModuleARouting()能够通过添加新模块或删除一个模块来动态地向我的应用程序添加一些路由路径。通过这种方式,每个模块都可以有自己的内部结构并AppRouting()合并它们。

但是,我不确定ModuleARoutingExtend(),更具体地说AppRoutingExtend()。在最后一个中,我尝试修改诸如App.RootModuleAContributorsRoute. 顺便说一句,我没有直接的信息ModuleARouting.call(this),我不知道变量的名称RootModuleAContributorsRoute。这就是我通过从ModuleARoutingExtend()Ember.Route.extend({/* some code *}) 获取“贡献者”及其值来使用 eval 动态的原因;

所以,我的问题是:有没有更好的方法为我的应用程序动态添加一些路由并获取它们的配置?如果没有,它仍然是一个好方法吗?

4

0 回答 0