在Ember中更改断开的链接图标
我尝试了通常的操作来更改断开的链接图标(请参见下文),但它们似乎并未在我的Ember应用程序中工作。在Ember中更改断开的链接图标
目前,模型从外部API获取数据。其中一条数据是链接网址。此链接URL(product_link
)被插入到该模板,具体地在这一点:
<img {{bind-attr src=product_link}} />
这是一个车把{{#each}}
回路的一部分。有几个链接指向死链接,我现在没有办法修复这些网址。我想用我自己的一个替换通用的断开图标链接。我怎样才能做到这一点?
事情我已经尝试:
<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
有什么建议?
您可以创建一个组件,如提到的@kaungst
,下面是具有另一个属性errorSrc
的组件的代码,如果未加载src
,将显示该组件。
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}}
很好用。谢谢。 – Josh 2014-11-24 16:18:26
Blessenm的解决方案是伟大的,但它修改了模型本身。我们不想这样做,所以我们创建了一个名为“安全图像”的组件,它向图像添加了一个“破碎”类。在破碎的图像上使用该类,我们可以使用css删除或更改损坏的图像。
{{safe-image src=product_link}}
带有此组件代码: 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();
}
});
,并将此CSS要么完全消除图像,或与我们选择的一个替换:
img.broken {
/* use this to show nothing: */
display: none;
/* or use this instead to replace the image: */
content:url("http://imgur.com/SZ8Cm.jpg");
}
两个Blessenm的德米特里·沃尔夫的解决方案的工作非常好。只需确保在设置错误回调中的属性之前组件尚未被销毁。
didInsertElement: function() {
this.$().on('error',() => {
if (!this.get('isDestroyed') {
this.set('src', this.get('errorSrc'));
}
});
},
我仍在学习如何使用它们,但这看起来像是一个组件的工作。 http://emberjs.com/guides/components/ – kaungst 2014-11-24 11:59:05