4

I have several functions that are used to bind events with divs on the page. There's MenuHandlers, CalendarHandlers, PopupHandlers....

So for the moment, I have a single function that's called BindHandlers that I call from the document ready function and that runs all the handler functions one by one.

Is there a one-liner solution that would say something like "call all the functions that have "Handlers" in their function name?

Here's what the function looks like:

function BindHandlers() {
  MenuHandlers();
  CalendarHandlers();
  PopupHandlers();
  ... 8 more like this
}

What I'm looking to replace:

BindHandlers(); // replace that line with the following:
"call all the functions that have "Handlers" in their names

Thanks for the suggestions.

frenchie
  • 51,731
  • 109
  • 304
  • 510
  • Why would you want to do it any other way? It couldn't possibly be any faster than just doing it one by one. – GoldenNewby Feb 17 '12 at 23:04
  • Are those functions global functions or properties of one of your objects? – Šime Vidas Feb 17 '12 at 23:05
  • beccause that way, if I add Handlers functions, they'll just get executed automatically. – frenchie Feb 17 '12 at 23:06
  • @ŠimeVidas: they're all globals – frenchie Feb 17 '12 at 23:06
  • Look at these answers for inspiration: http://stackoverflow.com/questions/912596/how-to-turn-a-string-into-a-javascript-function-call http://stackoverflow.com/questions/85992/how-do-i-enumerate-the-properties-of-a-javascript-object – blueberryfields Feb 17 '12 at 23:08
  • @frenchie The use of global variables should be minimized. Wrap your script in `(function () {...})` at least... – Šime Vidas Feb 17 '12 at 23:09
  • Look at these answers for inspiration: http://stackoverflow.com/questions/912596/how-to-turn-a-string-into-a-javascript-function-call http://stackoverflow.com/questions/85992/how-do-i-enumerate-the-properties-of-a-javascript-object – blueberryfields Feb 17 '12 at 23:09
  • Let us see that part of the `BindHandlers`-code where the other handlers are called. It seems like those handlers are called inproperly... – Teemu Feb 17 '12 at 23:13

2 Answers2

4

If these functions are all global, you could call all functions with Handlers in the name with something like this

for (var x in window)
    if (typeof window[x] === 'function' && /Handlers/.test(x))
         window[x]();

Here's a simple demo

Adam Rackis
  • 82,527
  • 56
  • 270
  • 393
  • Ok, that's really cool; not a one-liner but still solves the problem of having to register the handlers. – frenchie Feb 18 '12 at 12:29
0

Backbone has this:

events: {
    'click #menu'       : 'MenuHandler',
    'click #calendar'   : 'CalendarHandler',
    // etc.
}

The event binding is performed automatically when the corresponding view is created.

You could use this pattern:

bindEvents({
    'click #menu'       : 'MenuHandler',
    'click #calendar'   : 'CalendarHandler',
    // etc.
});
Šime Vidas
  • 182,163
  • 62
  • 281
  • 385