Adding and removing listeners

Benchmark created by David Mark on


Description

Basic DOM operation: adding and a listener to an element and then removing As an added challenge, the - this - object must be set for the listener. This gets really ugly in jQuery.

Preparation HTML

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
/*
 * Context here is an HTML5 document
 * Appropriate build for this context would exclude XHTML support
 * Next line asserts document will create an HTML DOM
 * There are virtually no documents on the Web that create an XHTML DOM
 *
 */
var API = { disableXmlParseMode:true };
</script>
<script src="//www.cinsoft.net/mylib099-min.js"></script>
<script>
  // For My Library test
  
  var attachListener = API.attachListener;
  var detachListener = API.detachListener;
  
  // For cross-browser test
  
  // NOTE: Should use isHostMethod for host method detection
  
  // Degrades below IE 9. Add attachEvent branch to support legacy versions.
  // Could even be done in a script inside conditional comments. ;)
  // Also degrades in browsers lacking native bind method (many)
  // Alternatively, use Function.prototype.call (adds back most of non-IE)
  
  if (document.documentElement && document.documentElement.addEventListener && Function.prototype.bind) {
    var attachEventListener = function(el, eventType, fn, thisObject) {
      var boundFunction = fn.bind(thisObject || el);
  
      el.addEventListener(eventType, boundFunction, false);
      return boundFunction; // NOTE: returns bound function for removal
    };
    var removeAttachedEventListener = function(el, eventType, fn) {
      el.removeEventListener(eventType, fn);
    };
  }
  
  // For all tests
  
  var el1 = document.createElement('div');
  var el2 = document.createElement('div');
  var el3 = document.createElement('div');
  var el4 = document.createElement('div');
  
  var listenerFunction = function() {
    var x = 1;
  };
  
  var thisObject = {};
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
My Library
attachListener(el1, 'click', listenerFunction, thisObject);
detachListener(el1, 'click', listenerFunction);
ready
My Library (OO)
E(el2).on('click', listenerFunction, thisObject).off('click', listenerFunction);
ready
jQuery
jQuery(el3).bind('click', jQuery.proxy(listenerFunction, thisObject)).unbind('click', jQuery.proxy(listenerFunction, thisObject));

// Apparently the only way to do this in one chain :(
// Breaking it in two or three wouldn't be in the spirit of jQuery.
ready
Cross-browser
if (attachEventListener) { // Conditionally defined
  removeAttachedEventListener(el4, 'click', attachEventListener(el4, 'click', listenerFunction, thisObject));
} else {
  throw new Error('Abort due to degraded browser');
}
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.

  • Revision 1: published by David Mark on