What performs better? 30 observers on specific elements or 1 Observer observing every click?

8 views
Skip to first unread message

Luke

unread,
Oct 14, 2011, 11:13:43 AM10/14/11
to prototype-s...@googlegroups.com
Hi there,

I'm working on a, well I dare to call it 'Webapp', that has lots of links that call JS functions. Now I'm wondering, instead of invoking ~30 click-observers, does it perform better to just invoke a single click-observer and use the findElement method to call the right function? I'm not sure because I'd need 30 if statements (maybe even more) on every click, which doesn't seem right either. Also, I find having 1 mega-function that calls all other function (software-architecture-wise) kinda ugly.

What would you recommend. Does using only 1 observer even boost the perfomance significantly?

Thanks
Lukas

Victor

unread,
Oct 17, 2011, 5:39:40 AM10/17/11
to prototype-s...@googlegroups.com
You can use some dispatching mechanism, e.g.:
1. HTML: all your clickable elements have special class or attribute like
  <a class="widget chooser">chooser</a>
or
  <a data-widget-type="chooser">chooser</a>
2. JS: your single observer finds somehow your desired element and dispatches event accordingly to the special class of element ("chooser" in this sample)
  var widgetType = element.readAttribute("data-widget-type") || "";
  if (widgetType && Widgets[widgetType]) {
    Widgets[widgetType].handleEvent(element);
  }

Luke

unread,
Oct 17, 2011, 11:51:04 AM10/17/11
to prototype-s...@googlegroups.com
Do I understand this right that you suggest adding one special class or attribute to all clickable elements, so that in my observer I can check for that class/attribute in the very first line minimizing the amount of if statements PLUS you suggest to delegate the triggered event to the [clicked] element so that I don't have one big eventhandler and can keep a good software structure?

If I understand this right this would be THE answer.

Victor

unread,
Oct 28, 2011, 4:29:13 AM10/28/11
to prototype-s...@googlegroups.com
you suggest adding one special class or attribute to all clickable elements, so that in my observer I can check for that class/attribute in the very first line minimizing the amount of if statements

yes
 
PLUS you suggest to delegate the triggered event to the [clicked] element

to module/class/etc., which is responsible for processing events on elements of this type
 
so that I don't have one big eventhandler and can keep a good software structure?

exactly

Also you can develop new modules without changing main event handler, and add/remove elements in document dynamically.

Reply all
Reply to author
Forward
0 new messages