Search code examples
javascriptobserver-patternunobtrusive-javascript

I'm trying to understand best practices for unobtrusive Javascript. What is the recommended and efficient way to use observers?


I'm trying to understand best practices for unobtrusive Javascript. Among the ideas of unobtrusive Javascript is that Javascript should not be directly included in the html code of the page, such as onchange=runScript(). Instead, an observer should be created to execute code whenever the element in question changes.

My questions are what the best practices are surrounding observers. How much overhead is there to an event observer in Javascript?

I don't know how observers are generally coded in browsers. Is it more efficient to create a single general observer that could handle a lot of elements but has to run code for each click, such as the following:

document.body.observe('click', function(event) {
  if (event.element().match('some_id')) {
    //do something
    event.stop()
  }
}

Or would it be more efficient to create a single observer for each relevant element that matches it very specifically, such as the following:

$('some_id').observe('click', function(event) {
  //do something
  event.stop()
}

Or are observers of such low overhead that there's no reason to worry about it at all, and I should just do whatever is more convenient to code?


Solution

  • Unqualified, "efficient" is too broad to say that a single technique is the most efficient. For example, there's time efficiency and space efficiency, and there's often a tradeoff between the two. Also, different browsers are free to implement events however they see fit, as long as they behave as the W3C events standard dictates, limiting what conclusions can be made about time and space costs.

    We can analyze costs and efficiencies in relation to event flow. In every compliant browser, an event first fires on the root element, then on each intervening child element until it reaches the target, then the event bubbles back up to the root, again firing on intervening elements. There will be a time cost in making each step down and up the document structure during event flow (figuring out which element to fire on, looking up the listeners &c.), so if you can stop an event as early as possible during flow (as in your first example) there is a potential time saving. Of course, special handling of each target may offset any gain and it may be incorrect to stop an event early.

    Creating a separate but equal listener function for each of a collection of elements may produce an unnecessary memory cost. Note this is not the same thing as subscribing the same function on multiple objects. For example:

    for (var i=0; i < elements.length; ++i) {
        elements[i].observe('click', function (evt) {...});
    }
    

    may require more memory than:

    elements.each('click', function (evt) {...});
    

    If the JS engine interns functions, the two will use the same amount of memory.

    One thing we can't assume is how event listeners are looked up, given an event and element. However, there typically aren't that many listeners for a given event and element, so the time or space efficiency of this shouldn't be a concern.

    In the end, browsers seem to implement events well enough that performance differences don't tend to be an issue. Simplicity and readability are thus more important than how you define and subscribe event listeners.