0

I would simply like to return two different values based on event handlers firing or not, the types are load and error.

function image(url) {

    var asset = new Image();
    asset.addEventListener("load", function() {
        // return the image here
    }, false);
    asset.addEventListener("error", function() {
        // return false
    }, false);
    asset.src = url;
};

I know I can't return from inside the event listener but how can I make it so that if there was an error image will return false, otherwise the image?

Example usage;

var img = image("BAD URL"); // false
var img2 = image("GOOD URL"); // Image object
GriffLab
  • 2,076
  • 3
  • 20
  • 21
  • 2
    You can't, it's as simple as that. You have to make `image` accept a callback, call it inside the event handlers and pass the result to it. See also: http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call. It's basically the same. – Felix Kling Jun 22 '13 at 22:32
  • 1
    Pass 2 callbacks into `image`, one for success, another for error. – elclanrs Jun 22 '13 at 22:34
  • @FelixKling Thanks for the link I should be able to sort it out now :) – GriffLab Jun 22 '13 at 22:38

0 Answers0