Really struggling with this one. I have a component responsible for rendering an image. I’m trying to make the component do this:
-show ‘loading’ div until image is loaded
-detect image load errors, replace src with “placeholder” image
-set property based on whether an image meets a certain size criteria (to determine whether a’larger image’ modal should function)
I’m running into all sorts of issues because when one of these state-related properties is set, the component refreshes, starting the whole process over.
Right now, I can’t even figure out how to get the “loading” state off. it seems like this could should work:
export default Component.extend({
imageSelector: '.main-image',
modalActive: false,
missingImage: 'Image-Coming-Soon.jpg',
isLoading: true,
didRender() {
this._super(...arguments);
let selector = get(this, 'imageSelector');
this.$(selector).on('error', () => {
let missing = get(this, 'missingImage')
set(this, 'productImage', missing);
this.$(selector).off('error');
});
this.$(selector).on('load', () => {
set(this, 'isLoading', false); // this doesn't turn off loading state
let width = this.$(selector).get(0).naturalWidth;
let height = this.$(selector).get(0).naturalHeight;
if (width >= 600 || height >= 600) {
set(this, 'modalActive', true);
}
this.$(selector).off('load');
});
},
willUpdate() {
// if, say, a different image on the page is clicked, reset loading state
this._super(...arguments);
set(this, 'isLoading', true);
}
});
with this component:
{{#if isLoading}}
<div class="product-image-loader">loading...</div>
{{else}}
<div class="image-container">
<a class="modal-link" href="#" {{action (action toggleImageModal) largeImage modalActive}}>
<img src="{{productImage}}" class="img-responsive main-image" />
</a>
</div>
{{/if}}
If I just set all the isLoading’s to false, it comes within the realm of working, but if I put console logs in the hooks and error/load conditions I see them multiple times in the same view. Like it’s recursing because of the state-change refreshes.
I could do all this with just jquery DOM manipulation, but I guess I’m not supposed to do that anymore
I’m either approaching this all wrong, or bumping against some unknown (to me) ember limitation. Any help appreciated!