views:

22

answers:

1

I understand why JSLint kicks up a warning here, but I don't know how else to write my code so it validates.

Here's a boiled down sample. In the code below, I have an object that I need to attach two event listeners to: one for "complete" and the other for "error". Each points to its own event handler. When either event handler is reached, I want to remove both event handlers. But I will always get a validation error when I try to remove the second event handler's listener from the first event handler.

var myFunction = function(obj) {
    var doComplete = function() {
        // ...Do something here to handle successful execution, then remove listeners
        obj.removeEventListener('complete',doComplete,true);
        obj.removeEventListener('error',handleError,true); // INVALID!
    };
    var handleError = function() {
        // ...Do some error handling here and then remove event listener
        obj.removeEventListener('complete',doComplete,true);
        obj.removeEventListener('error',handleError,true);
    };

    obj.addEventListener('complete',doComplete,true);
    obj.addEventListener('error',handleError,true);
    obj.load();
};

Whenever I get one of these warnings, it has always meant I'm doing something wrong, but in this case, I can't see how to get around the problem. Does anyone know what the right way is to do this?

The validation error is: Lint at line 5 character 41: 'handleError' is not defined. (the web client says Implied global: handleError 5)

+1  A: 

You need to rearrange your code slightly.

var myFunction = function(obj) {
    var doComplete, handleError;
    doComplete = function() {
        // ...Do something here to handle successful execution, then remove listeners
        obj.removeEventListener('complete',doComplete,true);
        obj.removeEventListener('error',handleError,true); // INVALID!
    };
    handleError = function() {
        // ...Do some error handling here and then remove event listener
        obj.removeEventListener('complete',doComplete,true);
        obj.removeEventListener('error',handleError,true);
    };

    obj.addEventListener('complete',doComplete,true);
    obj.addEventListener('error',handleError,true);
    obj.load();
};

JSLint expects to see a declaration of a variable before it's used. This change does so, even though it appears ineffective.

Dominic Mitchell
Ah. Of course. I don't like this much because having `var` before the function declaration helps me immediately identify private methods and spot scope problems. I may have to add something like `/* var */` in front of methods now. But for sure your answer works.
Andrew