Created
February 9, 2015 02:34
-
-
Save twokul/808e5d83d7cd78751d74 to your computer and use it in GitHub Desktop.
lazy-loading-image-in-ember
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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