在Ember中以编程方式创建新路由

9

我正在使用从服务器获取的JSON文件来配置我的网站,并告诉每个页面它的标题是什么。 JSON文件如下所示:

[{"route": "student", "title": "Student Info Page"}, {"route": "payments", "title": "Payments and Pricing"}, {"route": "policy", "title": "Mine"}, {"route": "biography", "title": "About Me"}]

这段代码用于创建一个导航栏:

App.MenuController = Ember.ArrayController.create();
$.get('config.json', function(data) {
    App.MenuController.set('content', data);
});

然后在模板中使用:

{{#each App.MenuController}}
    {{#varLink route this}}{{title}}{{/varLink}}
{{/each}}

到目前为止,一切都很顺利。

那么我的问题是:我想以编程方式使用此 JSON 对象确定应存在哪些路由,从而完成使用 App.Router.map 的路由映射。

我该如何做呢?我已经在文档中搜索过,并尝试了以下方法:

$.get('config.json', function(data) {
    App.MenuController.set('content', data);
    for (var i = 0; i < data.length; i++) {
        App.Router.map(function(){
            var r = data[i].route;
            console.log(r);
            this.route(r);
        });
    }
});

这将生成以下控制台输出:

student app.js:9
payments app.js:9
policy app.js:9
biography app.js:9
Assertion failed: The attempt to linkTo route 'student' failed. The router did not find 'student' in its possible routes: 'index' ember.js:361
Uncaught Error: There is no route named student.index ember.js:23900
1个回答

5
我用这个来动态创建路由:
App = Ember.Application.create();
App.MenuController = Ember.ArrayController.create();

App.deferReadiness();

simulateAjax(function(data) {
    App.MenuController.set("content", data);    
    App.Router.map(function() {
        var router = this;
        data.forEach(function(item) {
           router.route(item.route); 
        });
    });
    App.advanceReadiness();
});
simulateAjax是一个模拟向服务器发送ajax请求的函数。 App.deferReadiness();App.advanceReadiness();可以延迟应用程序的启动,以便在添加新路由时不会出现屏幕闪烁的效果。因为我们的应用程序准备好了:当路由被创建时,而不是文档准备好时。
这里有一个演示
更新: link-to辅助函数支持动态路由,使用对象和路径进行设置。 但目前需要使用ENV.HELPER_PARAM_LOOKUPS = true
有了这个,我们不需要创建一个自定义的linkTo来处理动态路径,就像第一个演示一样 ;)
这是一个新的演示

好的方法,这使得我悲观的回答过时了 :) - intuitivepixel
先生,您真是太棒了。 - blaineh
在ember-cli中有没有一种方法可以做到这一点? - iOS dev

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接