I've recently been doing some mods to some old code I've been maintaining for a couple of years now.
As part of a wider set of scripts using YAHOO YUI 2.2 (yes, that old) for dialog-style panels, I have a function that listens to click events on 3 buttons in a given panel set:
addFooListeners = function (panelType) {
YAHOO.util.Event.addListener("show" + panelType, "click", showFoo, eval(ns + ".panel_" + panelType), true);
YAHOO.util.Event.addListener("hide" + panelType, "click", hideFoo, eval(ns + ".panel_" + panelType), true);
YAHOO.util.Event.addListener("commit" + panelType, "click", commitFoo, eval(ns + ".panel_" + panelType), true);
}
This code is the result of a number of panels/dialogs having near identical behaviour.
For this round of development I've needed to add the ability to do things a little differently from time to time, so I added an object, overrides
which allows me to point the show
, hide
and commit
actions elsewhere. I came up with the following:
addFooListeners = function (panelType, overrides) {
var handlers = {
show: ( overrides != null ? ( overrides.show != null ? overrides.show : showFoo ) : showFoo ),
hide: ( overrides != null ? ( overrides.hide != null ? overrides.hide : hideFoo ) : hideFoo ),
commit: ( overrides != null ? ( overrides.commit != null ? overrides.commit : commitFoo ) : commitFoo )
}
YAHOO.util.Event.addListener("show" + panelType, "click", handlers.show, eval(ns + ".panel_" + panelType), true);
YAHOO.util.Event.addListener("hide" + panelType, "click", handlers.hide, eval(ns + ".panel_" + panelType), true);
YAHOO.util.Event.addListener("commit" + panelType, "click", handlers.commit, eval(ns + ".panel_" + panelType), true);
}
As you can see I'm enforcing default behaviour unless an appropriate attribute in the overrides
object is set with another function (named or anonymous).
Is there a cleaner / more readable way to concisely setup the handlers
object? The nested ternary seems to my eyes to be cluttering things a bit but other approaches like if ( overrides != null ) { ... }
seem just as messy.
?
ternary operator is worth using only when it's not nested. In your case it just makes the code more unreadable and unmaintainable. \$\endgroup\$