Josh Josh - 7 months ago 21
Javascript Question

Change broken link icon in Ember

I've tried the usual things to change the broken link icons (see below), but they don't seem to be working in my Ember app.

Currently, the model fetches the data from an external API. One of the pieces of data is a link url. This link url (

product_link
) is inserted into the template, specifically at this point:

<img {{bind-attr src=product_link}} />


This is part of a handlebars
{{#each}}
loop. Several of the links refer to dead URLs and I don't have a way to fix the URLs themselves at this moment. I'd like to replace the generic broken icon link with one of my own. How can I do this?

Things I've tried:

<img {{bind-attr src=favorite.product_image onError="this.onerror=null;this.src='/img/error.png';"}} />
//still shows the standard broken image icon


--

$('img').error(function(){
$(this).attr('src', 'img/error.png');
});
//nothing happens if I include this in a called javascript file


Any suggestions?

Answer

You can create a component like @kaungst mentioned, Below is the code for a component that has another attribute errorSrc which will be shown if the src isn't loaded.

Here is the working demo.

App.GracefulImageComponent = Ember.Component.extend({
    tagName: 'img',
    attributeBindings: ['src', 'errorSrc'],

    didInsertElement: function() {
        this.$().on('error', function() {
          this.set('src', this.get('errorSrc'));
        }.bind(this));
    },

    willDestroyElement: function(){
        this.$().off();
    }  
});

{{graceful-image src=item.image errorSrc=../model.errorImage}}