2

I would like your opinion on the following matter... I have a web application with some kind of panel with many buttons on it. Every button once clicked should have a separate function. I can see two implementations for this. First just enable a click watch event on every button separately, Second enable only one click watch event on parent element (panel) of buttons and then use a switch statement to find the button clicked and execute the appropriate function.

Which way is performance wise, better and lighter? having multiple watchers running simultaneously (first way), or only one watcher that runs a conditional statement every time? (second way).. Thanks!

mitsos1os
  • 2,170
  • 1
  • 20
  • 34
  • 3
    The single watcher will be faster to install, but slower at run time. Neither performance issue probably matters so you should select the option that makes your code the simplest and most maintainable. Object oriented principles often lead one to associate an event handler directly with the object where the event occurs and let the system handle the dispatching for you. I tend to start with that unless I have a reason to do differently. – jfriend00 Sep 19 '14 at 08:28
  • @jfriend00 Do 10-20 `$(document).on("click", "selector", ...` impact perfomance in notable way? Especially on mobile phones? – Regent Sep 19 '14 at 08:31
  • 1
    @Regent - 10-20 is a small number as long as the selector in your event handler isn't a time consuming one to calculate (each of those has to be calculated on every click). It is generally better to attach the event handler as close to the actual object as possible and not put all delegated event handlers on the root level `document` object because that is the slowest. This limits the number of selectors that have to be evaluated on any given click. – jfriend00 Sep 19 '14 at 08:55
  • 1
    See [this prior answer](http://stackoverflow.com/questions/12824549/should-all-jquery-events-be-bound-to-document/12824698#12824698) for some helpful info. – jfriend00 Sep 19 '14 at 08:56
  • I see.... In my case I believe I have to use the single watcher approach, because in the panel body, the buttons are dynamic and come and go, so I would have to control the watchers for each button every time they are created,, but with a single watch on their parent element (the panel) I don't have to worry about forgeting to enable a watcher. THanks – mitsos1os Sep 19 '14 at 09:29

0 Answers0