2014-11-24 66 views
5

我嘗試了通常的操作來更改斷開的鏈接圖標(請參見下文),但它們似乎並未在我的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 

有什麼建議?

+1

我仍在學習如何使用它們,但這看起來像是一個組件的工作。 http://emberjs.com/guides/components/ – kaungst 2014-11-24 11:59:05

回答

7

您可以創建一個組件,如提到的@kaungst,下面是具有另一個屬性errorSrc的組件的代碼,如果未加載src,將顯示該組件。

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}} 
+0

很好用。謝謝。 – Josh 2014-11-24 16:18:26

2

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"); 
} 
0

兩個Blessenm的德米特里·沃爾夫的解決方案的工作非常好。只需確保在設置錯誤回調中的屬性之前組件尚未被銷燬。

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