更换模型时,Ember #each内容不会更新

时间:2014-08-01 18:31:07

标签: ember.js

我有以下index.html

<!DOCTYPE html>
<html>
<body>
  <script type="text/x-handlebars" id="index">
    <ul>
    {{#each todo in todos}}
      <li>{{todo}}</li>
    {{/each}}
    </ul>
    <button {{action 'generate'}}/>Generate a to-do</buton>
  </script>

  <script src="js/libs/jquery-1.10.2.js"></script>
  <script src="js/libs/handlebars-1.1.2.js"></script>
  <script src="js/libs/ember-1.6.1.js"></script>
  <script src="js/app.js"></script>
</body>
</html>

app.js

App = Ember.Application.create();

App.Router.map(function() {});                                                                                                                                                                               

App.IndexRoute = Ember.Route.extend({
  model: function() {
    return {todos: ['To-do 1', 'To-do 2']};
  },
});

// This is a function I cannot change, because I don't own it.
// So I'm forced to get the updated model as the result of this.
// Here is some dummy-but-working implementation, for simulation purpose:
function generate(todolist) {
  var n = todolist.todos.length + 1;
  todolist.todos.push("To-do " + n);
  return todolist;
}

App.IndexController = Ember.ObjectController.extend({
  actions: {
    generate: function() {
      var oldToDoList = this.get('model');
      var newToDoList = generate(oldToDoList);
      this.set('model', newToDoList);
      console.log(this.get('model').todos);
    },
  },
});

当我点击 generate 按钮时,我在控制台中有效地看到了增长的待办事项数组,但是UI没有更新。

完全替换控制器模型后,#each内容不应自动更新,或者我遗漏了什么内容?

1 个答案:

答案 0 :(得分:1)

你的生成方法实际上并没有生成一个新数组,所以Ember没有注意到你已经改变了属性(因为它是对同一个数组的引用)。在您的特定实例中,您应该使用pushObject,而Ember会知道您正在修改相同的数组。

function generate(todolist) {
  var n = todolist.todos.length + 1;
  todolist.todos.pushObject("To-do " + n);
  return todolist;
}