Skip to content

Instantly share code, notes, and snippets.

@twokul
Created February 9, 2015 02:34
Show Gist options
  • Save twokul/808e5d83d7cd78751d74 to your computer and use it in GitHub Desktop.
Save twokul/808e5d83d7cd78751d74 to your computer and use it in GitHub Desktop.
lazy-loading-image-in-ember
import Ember from 'ember';
import { set } from 'ember';
import computed from 'ember/computed';
var on = Ember.on;
var getWithDefault = Ember.getWithDefault;
export default Mixin.create({
loaded: false,
errorThrown: false,
classNameBindings: ['loaded', 'errorThrown'],
defaultErrorText: computed('errorText', function() {
return getWithDefault(this, 'errorText', 'Image failed to load');
}),
_resolveImage: on('didInsertElement', function() {
var component = this;
var image = component.$('img');
var isCached = image[0].complete;
if (!isCached) {
image.on('load', function() {
component._imageLoaded();
});
image.on('error', function(error) {
component._imageError(error);
});
} else {
this._imageLoaded();
}
}),
_imageLoaded: function() {
var component = this;
run(function() {
set(component, 'loaded', true);
});
},
_imageError: function() {
var component = this;
run(function() {
set(component, 'errorThrown', true);
});
},
willDestroy: function() {
this.$('img').off('load');
this.$('img').off('error');
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment