我正在使用 ember.js 创建一个应用程序。我从 PRE.2 开始,但最终使用了 ember-data v11,因此升级为 ember 的 master。这意味着必须更改为新的 v2 路由器接口(interface)(作为旁注,我认为这要好得多,所以谢谢。)
我在试图弄清楚它是如何工作的时候遇到了一些问题,我深入了解了指南,但是有一些不一致的地方我无法完全理解:
1)
似乎有两种不同的约定用于配置路由映射:
在"template"部分,使用了 match().to() 接口(interface)
App.Router.map(function(match) {
match('/').to('index');
match('/posts').to('posts');
match('/posts/:post_id').to('post');
});
(Tom Dale 的 gist 中也使用了这种方法)
在“路由”部分中,使用了资源/路由接口(interface):
App.Router.map(function() {
this.resource('posts', function() {
this.route('new');
});
});
这里它指出“资源”应该用于名词路线,“路线”用于动词路线。
然后在“重定向到不同的 URL”部分,不遵循这个名词/动词约定:
App.Router.map(function(match) {
this.resource('topCharts', function() {
this.route('choose', { path: '/' });
this.route('albums');
this.route('songs');
this.route('artists');
this.route('playlists');
});
});
我的第一个问题是:
展望 future ,创建路线的正确约定是什么?
我的第二个问题紧随其后,与我的申请更相关:
如何从顶级“资源”路由链接到嵌套的“路由”路由并通过适当的模型?
(在"template"文档的“链接”部分中有一个示例,但它与 match().to() 接口(interface)有关,我专门使用资源/路由接口(interface))
这是我的例子:
我创建了一个基于流的简单站点结构,流由详细信息、一组帖子、句柄和历史记录组成。我的路由设置如下:
App.Router.map(function() {
this.resource('streams');
this.resource('stream', { path: '/stream/:stream_id' }, function(){
this.route('details');
this.route('posts');
this.route('handles');
this.route('history');
});
});
我的流路线如下所示:
App.StreamsRoute = Ember.Route.extend({
model: function() {
return App.Stream.find();
},
setupController: function(controller, model) {
controller.set('content', model);
}
});
和模板:
<script type="text/x-handlebars" data-template-name="streams">
<ul>
{{#each stream in controller}}
<li>{{#linkTo "stream" stream}} {{stream.title}} {{/linkTo}}</li>
{{/each}}
</ul>
</script>
我的流(单数)路线:
<script type="text/x-handlebars" data-template-name="stream">
<nav>
{{#linkTo "stream.details" }}Details{{/linkTo}}
</nav>
{{outlet}}
</script>
现在,我想链接到我的子路由“详细信息”,但我不确定在 linkTo 中放置什么,以便我的模型(它是一个流)被传递到这个子路由中:
App.StreamDetailsRoute = Ember.Route.extend({ });
我的“详细信息”模板仅显示流对象的一些属性。
<script type="text/x-handlebars" data-template-name="stream/details">
<h2>Stream Details</h2>
<p>Id: {{id}}</p>
<p>Title: {{title}}</p>
</script>
我还希望链接到帖子、历史记录和处理子路由,并能够基于流模型显示这些聚合。我不确定该怎么做。我假设我需要使用 setupController 来显示要显示的项目,我只是不确定如何将流对象放入这些子路由中。
最佳答案
Going forward, what is the proper convention for creating routes?
http://emberjs.com/guides/routing/defining-your-routes/ 中描述的资源/路由方法
How do I link from a top level "resource" route to a nested "route" route and pass through the appropriate models?
将路由的名称指定为第一个参数,后跟所需的任何上下文。因此,在您的示例中,从流模板创建指向“stream.details”的链接时,您需要指定
this
作为上下文。{{#linkTo "stream.details" this}}Details{{/linkTo}}
http://emberjs.com/guides/templates/links/ 中描述的方法仍然涵盖基础知识。
如有疑问,我建议检查 link_helper 的测试用例。例如:https://github.com/emberjs/ember.js/blob/master/packages/ember/tests/helpers/link_to_test.js#L249
关于Ember.js 路由器 v2 App.Router.map 文档不一致?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14370051/