我最近一直在学习Ember,我一直在玩他们网站指南部分的例子,我遇到以下片段的问题:
1)Javascript
App = Ember.Application.create();
App.Person = Ember.Object.extend({
firstName: null,
lastName: null,
fullName: function() {
return this.get('firstName') +
" " + this.get('lastName');
}.property('firstName', 'lastName')
});
App.ApplicationRoute = Ember.Route.extend({
model: function() {
var people = [
App.Person.create({
firstName: "Tom",
lastName: "Dale"
}),
App.Person.create({
firstName: "Yehuda",
lastName: "Katz"
})
];
return people;
}
});
2)HTML
<script type="text/x-handlebars">
<h1>People</h1>
<ul>
{{#each model}}
<li>Hello, <b>{{fullName}}</b>!</li>
{{/each}}
</ul>
</script>
当我导航到网站时,它会正确显示页面和名称。然后我导航到localhost:80 /#,它复制模板,以便一切都显示两次。当我使用浏览器的箭头控件来回导航时,每次都会在页面底部附加/复制模板。
老实说,我不明白为什么会那样做。想法?
答案 0 :(得分:2)
当您使用动态线段击中路线时,模型钩子会被踢掉,类似下面的内容更像是ember-esk
App = Ember.Application.create();
App.Person = Ember.Object.extend({
firstName: null,
lastName: null,
fullName: function() {
return this.get('firstName') +
" " + this.get('lastName');
}.property('firstName', 'lastName')
}).reopenClass({
people: [],
find: function() {
this.people.clear(); //so find doesn't create duplicates each time
var first = App.Person.create({ firstName: "Tom", lastName: "Dale" });
var last = App.Person.create({ firstName: "Yehuda", lastName: "Katz" });
this.people.pushObject(first);
this.people.pushObject(last);
return this.people;
}
});
App.ApplicationRoute = Ember.Route.extend({
model: function() {
return App.Person.find();
}
});
此外,您通常不使用基础应用程序模板/视图/控制器/路由中的“模型”,因此创建一个简单的模型并让该路由改为执行find()可能更有意义(以避免您遇到的重复问题)
答案 1 :(得分:1)
在Ember.js discussion forums上发布了另一条建议。感谢用户teddyzeenny。
在应用程序路由中返回模型会导致重新呈现。最好使用IndexRoute而不是ApplicationRoute。
1)Javascript
App = Ember.Application.create();
App.Person = Ember.Object.extend({
firstName: null,
lastName: null,
fullName: function() {
return this.get('firstName') +
" " + this.get('lastName');
}.property('firstName', 'lastName')
});
App.IndexRoute = Ember.Route.extend({
model: function() {
var people = [
App.Person.create({
firstName: "Tom",
lastName: "Dale"
}),
App.Person.create({
firstName: "Yehuda",
lastName: "Katz"
})
];
return people;
}
});
2)HTML
<script type="text/x-handlebars">
{{outlet}}
</script>
<script type="text/x-handlebars" id="index">
<h1>People</h1>
<ul>
{{#each model}}
<li>Hello, <b>{{fullName}}</b>!</li>
{{/each}}
</ul>
</script>
他在拉取请求中进行了更多讨论:
在ApplicationRoute中返回模型可能会导致应用程序 在某些情况下重新渲染的模板(as mentioned here)。
应用程序模板永远不应该重新渲染,因为它是附加的 到身体,因此在重新渲染时导致重复的模板。
此PR还会添加{{outlet}},因为有些人正在使用此功能 例如作为一个起点,有一个出口准备就绪 他们更容易建立在这个例子上。