vendredi 29 janvier 2016

Binding to a model relationship property fails in the each helper

Binding to a model relationship property fails in the each helper as demonstrated below:

Here are my models:

`//app/models/category.js
export default DS.Model.extend({
  name: DS.attr(),
  image: DS.belongsTo('image', { async: true }),
});

//app/models/image.js
export default DS.Model.extend({
  name: DS.attr('string'),
  thumbfullfilepath: DS.attr('string'),
  category: DS.belongsTo('category', { async: true })
});`

When I run the category model in the each handlebars helper below to retrieve the 'thumbfullfilepath' for an image tag, no value is bound to the img src:

`{{#each model as |category|}} 
    <div class="small-element item">
        <div class="cat-name"><a href="#">{{category.name}}</a></div>
        <div class="cat-name edit">{{#link-to 'admin.categories.edit' category}}Edit{{/link-to}}</div>
        <span class="entry-thumb">
            <img src={{category.image.thumbfullfilepath}} alt="">
        </span>   
    </div>
{{/each}}`

However, I have verified the relationship binding works on display of a single model as when I visit the "admin.categories.edit" route which loads a single category model, the {{category.image.thumbfullfilepath}} path is retrieved and reflected in the template. This has led me to believe that for some reason, model relationship bindings fail in the each handlebars helper within templates.

Would someone shed some light here.

## The solution that has worked for me

I created an image component "image-atom" whose component.js is as below:

`//pods/components/image-atom.js
export default Ember.Component.extend({
  tagName: 'img',
  attributeBindings: ['src', 'alt'],
  alt: '',
  src: Ember.computed(function () {
    this.get('source').then((image) => {
        this.set('src', image.get('thumbfullfilepath'));
    });
    return null;
  })
});`

Which I use like so here below and it works but it feels hacky:

`{{#each model as |category|}} 
    <div class="small-element item">
        <div class="cat-name"><a href="#">{{category.name}}</a></div>
        <span class="entry-thumb">
          {{image-atom source=category.image alt=""}}
        </span>   
    </div>
{{/each}}`

Here below are the environment details:

(a). ember cli version: "2.2.0-beta.2" (b). ember-data: "^2.2.1" (c). ember: "2.2.0" (d). node: "0.12.7" (e). npm: "2.14.10" (f). os: "darwin x64 El Capitan"

Let me know.




Aucun commentaire:

Enregistrer un commentaire