How to store an event-handler in a variable and bind it to an object later?

event-handling, events, javascript, jquery, jquery-events

Solution

My suggestion is to go a different route: Bind the events and leave them bound for the complete lifecycle of the page. In the event handler, check for the state of the relevant objects and decide what to do with the event - this might include simply ignoring it.

There are two rationales behind that:

- Keep it simple and debugable

- I have seen delivery of an event delayed so long, that the state at the initiation of the event was no longer the same as on event delivery: i.e.: Your event is delivered, after you have unbound it (as it was initiated while still bound)

Problem

Basically I have a button Delete Selected, which is disabled as long as no checkboxes are selected. As soon as the user checks a checkbox, I'd like to bind a click event-handler to this button. As it can happen that the user deselects the checkboxes and none is selected, I wanted to store the complete event-handler function in a variable and only bind it as soon as checkboxes are checked. The question is: how can I store this event-handler function in a variable to most easily bind it to an object? Till now I only used this to unbind an event-handler (that already existed on this object) and then bind it again, like this: ``` $(my-selector).unbind('click', eventHandler); $(my-selector).bind('click', eventHandler); ``` ...but never the other way round.

Original source