-
-
Save user24/1397774 to your computer and use it in GitHub Desktop.
var handling = false; | |
window.onSomeEvent = function handleEvent() { | |
if(handling) return; | |
handling = true; | |
/* some other handler code here which eventually switches handling off again */ | |
}; |
var handling = false; | |
window.onSomeEvent = function handleEvent() { | |
handling ? return : handling = true; | |
/* some other handler code here which eventually switches handling off again */ | |
}; |
var handling = false; | |
window.onSomeEvent = function handleEvent() { | |
if(handling) { | |
return; | |
} | |
handling = true; | |
/* some other handler code here which eventually switches handling off again */ | |
}; |
var handling = false; | |
window.onSomeEvent = function handleEvent() { | |
if(handling) { | |
return; | |
} else { | |
handling = true; | |
/* some other handler code here which eventually switches handling off again */ | |
} | |
}; |
Really? I find Option 3 much more appealing than Option 4; Option 4 just indents the bulk of the handler for no good reason.
In order, I prefer:
1,3,4,2
Although I'm happy to accept 3,1,4,2
Bear in mind that these options are designed for the case where the code inside the if is only that one return line. For other cases, option 4 is probably best.
And that fact may be good reason to advocate option 4 at all times for the simplicity of the rule, rather than option 4 for most cases but sometimes option 3/1 depending on if it's only short.
Option five is more complex, but arguably simpler to use:
window.onSomeEvent = myLibrary.lockHandler(function handleEvent() {
/* some other handler code here */
myLibrary.releaseHandlerLock();
});
Where myLibrary abstracts away all the finnicky handling=true stuff.
But the problem with that is you quickly discover this anti-pattern:
window.onSomeEvent = myLibrary.loggingHandler(myLibrary.callbackStack(myLibrary.lockHandler(function handleEvent() {
/* some other handler code here */
myLibrary.releaseHandlerLock();
})));
and so on, moving the little bits of complexity away from the code and into this weird chain of augmenting callbacks.
Callback stacks? Can't you just use objects?
The last one seems most pleasing to me.