3

我最近一直在学习 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/#,它会复制模板,以便所有内容都显示两次。当我使用浏览器的箭头控件来回导航时,每次都会在页面底部附加/复制模板。

老实说,我不明白为什么会这样。想法?

4

2 回答 2

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() 可能更有意义(以避免重复问题你遇到了)

于 2013-04-04T15:14:07.340 回答
1

在 Ember.js讨论论坛上发布了另一个建议。归功于用户 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 中返回模型可能会导致应用程序模板在某些情况下重新渲染(如此处所述)。

应用程序模板永远不应该重新渲染,因为它附加到正文中,因此在重新渲染时会导致重复的模板。

这个 PR 还添加了一个 {{outlet}},由于有些人使用这个示例作为起点,准备好一个 outlet 将使他们更容易在示例的基础上进行构建。

于 2013-04-05T13:28:20.280 回答