Not sure how useful this is, but this uses javascript Image() and a promise to load an image. Allows you to set loading and error states.
import Ember from 'ember';
const {
Component,
get,
set
} = Ember;
export default Component.extend({
isLoading: true,
isError: false,
/* JavaScript Image Object used to do the loading */
imageLoader: Ember.computed(function() {
return new Image();
},
getImage(url, _this) {
return new Ember.RSVP.Promise((resolve, reject) => {
let img = _this.get('imageLoader');
img.onload = function() {
resolve(url)
}
img.onerror = function() {
reject(url)
}
img.src = url
});
},
didInsertElement() {
this._super(...arguments);
let _this = this;
let src = get(_this, 'src');
_this.get('getImage')(src, _this).then(success => {
console.log("success", success);
set(_this, 'isLoading', false);
}).catch(error => {
console.log("fail", error);
set(_this, 'isLoading', false);
set(_this, 'isError', true);
})
},
willDestroyElement() {
this._super(...arguments);
let img = get(this, 'imageLoader');
if (img) {
img = img.onload = img.onerror = null;
this.set('imageLoader', null);
}
}
});
Then in the template you could do something like:
{{#if isLoading}}
loading...
{{else}}
{{#if isError}}
{{else}}
{{/if}}
{{/if}}
If the component is called "product-render" you could use it in parent template like:
{{product-render src=myImage}}
No comments:
Post a Comment