Chr*_*oft 5 javascript handlebars.js ember.js
在EmberJS网站上运行入门教程时,有些事情让我有点困惑.
有一点需要注意的是,我决定使用带有把手2.0.0的ember 1.9.0beta4而不是初学者包中包含的1.8.1/1.3.0.
首先是截屏视频中包含的代码:
app.js
App.Router.map(function() {
this.resource('about');
this.resource('posts');
this.resource('post', {path: ':post_id'})
});
App.PostsRoute = Ember.Route.extend({
model: function() {
return posts;
}
});
Run Code Online (Sandbox Code Playgroud)
和
index.html
{{#each model}}
<tr><td>
{{#link-to 'post' this}}
{{title}} <small class='muted'>by {{author.name}}</small>
{{/link-to}}
</td></tr>
{{/each}}
Run Code Online (Sandbox Code Playgroud)
这与预期完全一致,单击时会显示请求的帖子.
但是,因为我使用的是1.9.0,所以前面的代码会产生一个弃用的警告{{#each}},告诉我改为使用{{#each foo in bar}}.我理解为什么会出现并同意详细程度有助于准确显示正在循环的数据.
所以我改变线{{#each model}}对{{#each post in model}}和数据的每一位消失了......然后我试图改变的代码:
updated index.html
{{#each post in model}}
<tr><td>
{{#link-to 'post' this}}
{{post.title}} <small class='muted'>by {{post.author.name}}</small>
{{/link-to}}
</td></tr>
{{/each}}
Run Code Online (Sandbox Code Playgroud)
大!每个帖子再次出现标题和作者姓名.但点击任一帖子给我一个未定义id.我{{#link-to 'post' this}}改为{{#link-to 'post' this.id}}.结果相同.我改成了{{#link-to 'post' post.id}}.在id现在包含但是当我点击链接我得到这个错误:
Error while processing route: post Assertion Failed: You used the dynamic segment
post_id in your route post, but App.Post did not exist and you did not override
your route's `model` hook.
Run Code Online (Sandbox Code Playgroud)
我的问题是:
post.如果我只是包含post in代码,内部会发生什么强制前缀?对我来说,我应该能够使用this或继续不需要任何前缀.
添加post in到每个语句后,会发生什么this?为什么它不再引用同一个对象?
如何命名模型以便更容易分类?post in model应该是,post in posts但我还没有找到一种方法来命名数据容器.
现在我不再将模型称为模型,导致错误的原因是什么this?如何补救?
each post in ...您的沮丧和疑问正是第一个语法被弃用并且仅支持表单的原因。希望这能回答您的问题,如果您需要澄清,请回复。
在您使用的第一个示例中each model,块的范围更改为帖子,意思this是指循环中的当前帖子。当您形成表单时each post in ...,范围不会改变。当它没有改变时,这意味着this实际上指的是先前的范围(循环之前)。在您的示例中,前面的作用域是数组控制器,而不是 post 对象。
这与问题 1 相关。对于格式each post in ...,this指的是each块之外的任何内容。并不是某件事发生了this,而是某件事没有发生,this因为范围没有改变。
为了更好地命名,我通常设置一个属性作为数组控制器中内容的别名:
posts: Ember.computed.alias('content')
在您原来的示例中,当您link-to为助手提供 时this,您将传递完整的 post 对象。从您的尝试来看,这似乎是您没有做的一件事:
{#link-to 'post' post}}
| 归档时间: |
|
| 查看次数: |
143 次 |
| 最近记录: |