I have two very similar functions that exist mainly for syntactic sugar.
deactivate = (el, seek) -> el.find(seek).removeClass("active")
activate = (el, seek) -> el.find(seek).addClass("active")
This allows me to write, for example:
activate $("#something"), ".child"
Using the above purely as an example, ignoring any logical errors with the JavaScript itself... how could this be refactored to be more dry?
2 Answers 2
You can use js' bracket notation for this task
alter = (el, seek, method) -> el.find(seek)[method + "Class"]("active")
#use like this:
alter $("#something"), ".child", "add"
However, your situation doesn't really call for DRYness. Your method names make more sense than alter
, or whichever name you may choose.
-
\$\begingroup\$ You could just use your
alter
function as a stepping stone for the definitions ofactivate
/deactivate
become more DRY:deactivate = (el, seek) -> alter el, seek, "remove"
activate = (el, seek) -> alter el, seek, "add"
(Disclamer: I don't use CoffeScript) \$\endgroup\$RoToRa– RoToRa2011年12月19日 13:56:52 +00:00Commented Dec 19, 2011 at 13:56 -
\$\begingroup\$ @RoToRa Correct, and you can also do it the other way around: Store
activate
anddeactivate
on an object, and pass which one you want as an argument toalter
:containingObject[method]("active")
\$\endgroup\$Zirak– Zirak2011年12月19日 14:05:17 +00:00Commented Dec 19, 2011 at 14:05 -
\$\begingroup\$ Thank you. I think the syntactic benefit of my initial functions outweigh the benefit of making the code more DRY. I was just wondering if there was something I was missing here. \$\endgroup\$Toast– Toast2011年12月19日 20:43:29 +00:00Commented Dec 19, 2011 at 20:43
I think your code is fine. I would only suggest a more complex solution only if this pattern happens more often.
For example, if you want to refactor to allow for other class names you can do something like this:
adder = clsName -> (el, seek) -> el.find(seek).removeClass(clsName)
remover = clsName -> (el, seek) -> el.find(seek).addClass(clsName)
activate = adder 'active'
deactivate = remover 'active'