vendredi 5 juin 2015

EmberJS - access properties of an object by arbitrary key in a template and have those properties bound using HTMLBars?

With Handlebars I could do this:

<script type="text/x-handlebars" data-template-name="index">
  <table>
  {{#each model as |item index|}}
    <tr {{action 'update' index}}>
      {{#each col in columns}}
        <td>{{dd item col}}</td>
      {{/each}}
    </tr>
  {{/each}}
  </table>
</script>

App = Ember.Application.create();

App.IndexRoute = Ember.Route.extend({
  model: function() {
    return [
      { name: "Joe", description: "Good guy", age: 15 },
      { name: "Moe", description: "Bad guy", age: 25 },
      { name: "Dude", description: "Some other guy", age: 65 }
    ];
  }
});

App.IndexController = Ember.ArrayController.extend({
  columns : ['age', 'name', 'description'],
  actions: {
    update: function(index) {
      var item = this.get('model')[index];
      Ember.set(item, 'age', 10);
    }
  }
});

Ember.Handlebars.registerBoundHelper('dd', function(item, column) {
  return item[column];
}, 'age', 'name', 'description');

This binds the age, name & description properties of each item in the model so that changing the age property updates the template.

However now that HTMLBars is the default I can't do this because it seems that makeBoundHelper doesn't have a dependentKeys parameters like HandleBars does. This helper renders the objects fine but doesn't update when the data changes:

App.ddHelper = Ember.HTMLBars.makeBoundHelper(function(params) {
  var item = params[0];
  var column = params[1];
  return item[column];
}, 'age', 'name', 'description');

Ember.HTMLBars._registerHelper('dd', App.ddHelper);

So how do I access properties of an object by arbitrary key in a template and have those properties bound using HTMLBars?




Aucun commentaire:

Enregistrer un commentaire