I have created my own little image slider, and to get the loader working I had to create an addEventListener
and then append the loaded image into the DOM.
However, there's a bug in this scenario: When an image takes a while to load and the user clicks past it before it is loaded to see the next image, the event listener is still working in the background, and when the image is then fully loaded it overwrites what the user is currently looking at.
My HTML:
<template name="ImageGallery">
{{#each galleryImages}}
{{#if viewingImage}}
{{> Image}}
{{/if}}
{{/each}}
</template>
<template name="Image">
<div class="image-in-gallery">LOADING</div>
</template>
Checking if the "image" the user wants to see is the one we have hit in the each
iteration (thus displaying it):
Template.ImageGallery.helpers({
viewingImage: function() {
var self = this
var galleryImages = Template.parentData().galleryImages
var renderImage = false
var viewing = Template.instance().viewingImage.get()
var posOfThisImage = lodash.indexOf(galleryImages, self)
if (viewing === posOfThisImage) {
renderImage = true
}
return renderImage
}
})
Enabling the user to see the next "image" and looping if we have hit the end:
Template.ImageGallery.events({
'click .click-to-see-next-image': function(event, template) {
var viewing = template.viewingImage.get()
var imageCount = this.galleryImages.length
var nextImage = ++viewing
if (nextImage < imageCount) {
template.viewingImage.set(nextImage)
}
else {
template.viewingImage.set(0)
}
}
})
The loader:
Template.Image.onRendered({
var imageUrl = Template.currentData().name + Template.parentData().name + '.jpg'
var imageObj = new Image()
imageObj.src = imageUrl
imageObj.addEventListener('load', function() {
$('.image-in-gallery').empty()
$('.image-in-gallery').append($(imageObj))
}
})
You can see where the problem lies: the empty()
and append()
of course overwrites the image the user currently looking at and sets it to be whatever is next loaded.
I want to add a break somehow in the addEventListener
function to see if the image that is loaded is actually the one the user wants to see. But there are two problems:
1) The ReactiveVar
variable isn't available in this template. Do I need to use a Session
variable after all?
2) I have no idea how to break.
Can anyone help?