1
\$\begingroup\$

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?

asked Dec 19, 2011 at 13:27
\$\endgroup\$

2 Answers 2

2
\$\begingroup\$

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.

answered Dec 19, 2011 at 13:40
\$\endgroup\$
3
  • \$\begingroup\$ You could just use your alter function as a stepping stone for the definitions of activate/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\$ Commented Dec 19, 2011 at 13:56
  • \$\begingroup\$ @RoToRa Correct, and you can also do it the other way around: Store activate and deactivate on an object, and pass which one you want as an argument to alter: containingObject[method]("active") \$\endgroup\$ Commented 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\$ Commented Dec 19, 2011 at 20:43
1
\$\begingroup\$

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'
answered Dec 19, 2011 at 15:10
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.