Search code examples
javascriptjqueryonerror

What variables are in the scope of an image .onerror call?


I've got the following function in a project I'm working on:

var makePreviewSimulationDiv = function(){
    var errorFlag = false;

    imgError = function(image){
        errorFlag = true;
    };

    var that = this, proxy = new IAProxy(),
        //imageSource = real_image_source,
        imageSource = "",
        image = that.append('<img class="foo" onerror="imgError(this);
                            "src=' + imageSource + '></img>')
                    .children('.sim-ui-preview-sim-image'),
        container = image.run(encapsulateImg),
        iconsDiv = that.append('<div class="bar"></div>')
                       .children('.bar');

    if (!errorFlag){
        image.load(function(){
            container.run(zoomMaxWidth)
                .run(makeDraggable)
                .run(makeZoomable);
        });
    } else{
        alert('image load error!');
    }

    return that;
};

Currently, I have the image src set to "" to try to debug the behavior of the function if it gets a bad image src or no image src in an effort to make it fail gracefully. Currently, my code is correctly catching the error and throwing alert('image load error!');. However, if I locally scope my imgError function, i.e. change the code to the following:

    var imgError = function(image){
        errorFlag = true;
    };

imgError can no longer be found when onerror triggers on the image load. What is the scope of the function called in onerror, and can I move imgError into it's scope without declaring it globally and while still being able to access errorFlag from within imgError?


Solution

  • create the image with

    var img = new Image()
    

    bind to it's error and load handlers and set it's src with

    $(img).on("load",loadHandler).on("error",errorHandler)[0].src = imageSource;
    

    Now, inside of both of aforementioned handlers, you have access to this and the first argument of said handlers will be the event object.

    function errorHandler(event) {
        console.log(event);
    }
    function loadHandler(event) {
        console.log(event);
        $(this).appendTo("#imgHolder");
    }