Search code examples
javascriptjsfprototypejsdom-events

Event.observe inefficient with prototype Javascript, alternatives?


We have a table with a lot of checkboxes, onchange of a checkbox we want to call some Javascript. We use something similar to this snippet:

addEventObserver(elementId){
        // ($= means 'ends with') this is required for elementIds which are in a table and get prepended with some id
        $$('[id$=:'+elementId+']').each(function(e) {
            Event.observe(e, 'change', function(event) {
                submitAction(something);
            });
        });
}

So below an input checkbox we add a Javascript function call:

<input type="checkbox" name="somename" id="somePrependedIdsomeId">    
<script type="text/javascript" language="javascript">
                    addEventObserver('someId');
                </script>

this works fine with our test environment settings. In production though we have tables with ~700 checkboxes and this makes the browser/cpu get stuck.

We use jsf


Solution

  • I would scrap adding an event listener to every single checkbox in favour of writing a single "smart" event handler attached to a container element. Here is a simple example:

    var theDiv = document.getElementById("foo");
    theDiv.onchange = function(e) {
        if (e.target.tagName.toLowerCase() == "input" 
              && e.target.type.toLowerCase() == "checkbox") {
            alert("do something");
        }
    }
    

    Demo: http://jsfiddle.net/xFC3A/

    The onchange event is thus captured by the container div which is bubbles up to. The event attached to the div can test for the type of element that triggered the event (the source/target element depending on the browser) and react accordingly. Main advantages are:

    1. Only one event handler - no time wasted binding handlers to hundreds of elements.
    2. It will continue to work on dynamically added elements (via AJAX, JS etc.).

    Read more about Event Delegation.

    Some useful reference: http://www.quirksmode.org/js/events_properties.html