3
\$\begingroup\$

Very similar to this question, I'm curious about common patterns/best practices for handling events in coffeescript classes, particularly when you also need to call the event handlers immediately to initialize state.

Unlike the answer to the question above though, let's assume though that you do need/want a class.

Here's a contrived example:

class @Foo
  constructor ->
    @bar = new Bar()

    @checkbox = $('#my-checkbox')

    # set up the events
    @checkbox.click => 
      @bar.clickHandler(@checkbox)
      @clickHandler(@checkbox)

    # initialize state
    @bar.clickHandler(@checkbox)
    @clickHandler(@checkbox)

  clickHandler: ($elt) ->
    if $elt.is(':checked')
      # something
    else
      # something else

$ ->
  window.foo = Foo.new

Is there a usual pattern for cases like this where you want the event function called both when the event fires and when the class loads? I really hate the duplication but I'm not sure how to remove it. Any other suggestions?

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

I'm only vaguely familiar with coffeescript, but it seems like the issue is not that you need to call the event handler on init, it's that you need to call the logic currently residing in your event handler. If you separate your logic into reusable pieces, you can call this other method to execute your init logic. Without the complete code, it's hard to see what that logic is (by the way, incomplete code examples don't bode well for the Code Review site).

Consider something like this example though (sorry, pseudocode not coffeescript):

function init() {
    hideUserInformation();
}

function checkBoxChangeHandler(checkBox) {
    if(checkBox.checked) {
        hideUserInformation();
    } else {
        showUserInformation();
    }
}

function hideUserInformation() {
    // Some logic.
}

function showUserInformation() {
    // Some logic.
}

Now the event handler is only concerned with forwarding to the real logic, and you aren't trying to call an event handler with bogus arguments just to try to run the same code.

\$\endgroup\$
2
  • \$\begingroup\$ Thanks, I think the point about extracting the handler logic is a good one. However, using your code example, init() would need to either call showUserInformation() or hideUserInformation() based on the state of the checkbox. Not sure how to do that without calling the event handler with bogus arguments or duplicating the logic. \$\endgroup\$
    – Jared
    Commented Jun 26, 2014 at 0:03
  • \$\begingroup\$ I also had a typo in my example, calling changeHandler instead of clickHandler, I updated the example. \$\endgroup\$
    – Jared
    Commented Jun 26, 2014 at 0:15

Not the answer you're looking for? Browse other questions tagged or ask your own question.