Change the invisible link icon in Ember

I tried the usual things to change the icons with broken links (see below), but they don't seem to work in my Ember app.

The model is currently retrieving data from an external API. One part of the data is the URL of the link. This link url ( product_link ) is inserted into the template, in particular at this point:

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

This is part of the pen loop {{#each}} . Some links link to dead URLs, and I cannot fix the URLs themselves at the moment. I would like to replace the common broken link to the icon with one of my own. How can i do this?

Things I 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?

+5
source share
3 answers

You can create the mentioned component, for example @kaungst . Below is the code for a component with a different errorSrc attribute, which will be displayed if src not loaded.

Here is a 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}} 
+7
source

Blessenm's solution was great, but it modifies the model itself. We did not want to do this, so we created a component called a “secure image” that adds a class to the break. With this class on broken images, we can use css to remove or modify a broken image.

 {{safe-image src=product_link}} 

with this component code: import Ember from 'ember';

 App.SafeImageComponent = Ember.Component.extend({ tagName: 'img', attributeBindings: ['src'], classNameBindings: ['isBroken:broken'], isBroken: false, didInsertElement: function() { this.$().on('error', function() { this.set('isBroken', true); }.bind(this)); }, willDestroyElement: function(){ this.$().off(); } }); 

And added this css to either completely remove the image or replace it with one of our options:

 img.broken { /* use this to show nothing: */ display: none; /* or use this instead to replace the image: */ content:url("http://imgur.com/SZ8Cm.jpg"); } 
+2
source

Both Blessenm Dmitri Wolf solutions work very well. Just make sure the component has not been destroyed before setting the property in the callback.

  didInsertElement: function() { this.$().on('error', () => { if (!this.get('isDestroyed') { this.set('src', this.get('errorSrc')); } }); }, 
0
source

Source: https://habr.com/ru/post/1207551/


All Articles