Skip to content

Instantly share code, notes, and snippets.

@user24
Created November 27, 2011 16:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save user24/1397774 to your computer and use it in GitHub Desktop.
Save user24/1397774 to your computer and use it in GitHub Desktop.
various code style options
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 */
}
};
@tcrayford
Copy link

The last one seems most pleasing to me.

@user24
Copy link
Author

user24 commented Nov 27, 2011

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.

@tcrayford
Copy link

Callback stacks? Can't you just use objects?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment