Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't handlebars {{#each}} rerender when reordering list?

I am trying to manage the sorted display of an array of objects based on a toggled property on a controller. Because of this i'm unable to use the default sortProperties available to an ArrayController.

The expected result is that when I first click on the "edit" button i'm able to make changes to the items and when I click save it should re-render the {{#each}} block to show the new order of names.

Is this a bug in handlebars or am I doing something wrong?

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');
    }
  }

});
like image 724
Joel T Avatar asked Nov 01 '22 02:11

Joel T


1 Answers

You can get it working like this

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');
        }
    }
});
like image 71
Myslik Avatar answered Nov 12 '22 21:11

Myslik