重新排序列表时,为什么没有把手{{#each}}重新登记?

时间:2014-04-07 18:13:21

标签: javascript ember.js handlebars.js

我正在尝试根据控制器上的切换属性管理对象数组的排序显示。因此,我无法使用sortProperties可用的默认ArrayController

预期的结果是,当我第一次点击"编辑"按钮我能够对项目进行更改,当我单击保存时,它应重新呈现{{#each}}块以显示新的名称顺序。

这是车把上的错误还是我做错了什么?

JSBin:Handlebars not re-rendering when property toggled

HTML:

<script type="text/x-handlebars">
 {{outlet}}
</script>

<script type="text/x-handlebars" data-template-name="index">
  <h4>Raw \{{sorted_list}} property</h4>
    {{sorted_list}}<br/>
  <h4>Iterated `\{{#each item in sorted_list}}` property</h4>
  <ul>
    {{#each item in sorted_list}}
      {{#if editing}}
        <li>{{input type="text" value=item.name}}</li>
      {{else}}
        {{item.name}}<br/>
      {{/if}}
    {{/each}}
  </ul>
  {{#if editing}}
    <button {{action "edit_stuff"}}>Save</button>
  {{else}}
    <button {{action "edit_stuff"}}>Edit</button>
  {{/if}}
</script>

JS:

var App = Ember.Application.create();

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

App.Person = Ember.Object.extend({
  toString: function() {
    return this.name;
  }
});

App.IndexRoute = Ember.Route.extend({
  model: function() {
    return [
      App.Person.create({name: "Jules"}),
      App.Person.create({name: "Zed"}),
      App.Person.create({name: "Vincent"})
    ];
  }
});

App.IndexController = Ember.ArrayController.extend({
  editing: false,
  sorted_list: (function() {
    return this.sort_people();
  }).property('editing'),
  sort_people: function() {
    var sorted;
    sorted = this.get('content');
    sorted.sort(function(a, b) {
      return Ember.compare(a.name, b.name);
    });
    this.set('content', sorted);
    return sorted;
  },
  actions: {
    edit_stuff: function() {
      this.sort_people();
      this.toggleProperty('editing');
    }
  }

});

1 个答案:

答案 0 :(得分:2)

你可以像这样工作

App.IndexController = Ember.ArrayController.extend({
    editing: false,
    sorted_list: (function() {
        return this.get('content').sortBy('name');
    }).property('editing'),
    actions: {
        edit_stuff: function() {
            this.toggleProperty('editing');
        }
    }
});