I have a function which receives either a preloaded JS image object or an image url. This is passed in as the photo variable.
I perform a check to see whether the ‘photo’ var is a string or not. If it is I create a new image object and use the onload event to fire the generateSlide() function passing in the newly created image object as seen below:
renderSlide: function (slideindex, photo, external, count, text) {
var self = this;
var image = new Image();
if (typeof (photo) == 'string') {
image.onload = function () {
self.generateSlide(slideindex, image, external, count, text);
};
image.src = photo;
} else {
image.src = photo.src;
self.generateSlide(slideindex, image, external, count, text);
}
},
If the ‘photo’ var is a preloaded JS image object I simply run the function itself passing the image object into generateSlide();
Everything works great however for some reason in IE 9 I cannot simply pass through the ‘photo’ var directly into the generateSlide() function. I have to create a new image object and set the src to match the photo object’s src attribute.
This makes no sense to me and I can’t understand why this would be?
In the cases where the photo var is an actual JS image object it is confirmed as loaded elsewhere. ( I am preloading assets );
In summary, the code above works fine but can anyone explain WHY I have to create a new image object and cannot simple pass in the original one? Is there a more elegant solution? So far I haven’t noticed any problems with the above method but is anyone aware of any pitfalls using this approach.
Thanks in advance
It sounds like an issue with scope. Have you tried putting the call in a closure to make sure the correct photo is captured?
},