Improving Function.prototype.bind

Andrea Giammarchi andrea.giammarchi at gmail.com
Mon Jan 9 02:08:37 PST 2012


Just to make the second proposal easier to understand:


// abstract __proto__
var AbstractEventHandler = {
  // invoked when events are fired
  handleEvent: function (e) {
    var
      events = this.events,
      type = e.type
    ;
    if (events.hasOwnProperty(type)) {
      events[type].call(this, e);
    }
  },
  // shortcut to drop events
  cancelEvent: function (e) {
    (e.currentTarget || document).removeEventListener(
      e.type, this, e.eventPhase !== e.BUBBLING_PHASE
    );
  }
};

// generic "class"
function WhateverUIClass(){}
// extends AbstractEventHandler
WhateverUIClass.prototype = Object.create(
  WhateverUIClass.prototype,
  {
    // extends AbstractEventHandler
    handleEvent: {value: AbstractEventHandler.handleEvent},
    cancelEvent: {value: AbstractEventHandler.cancelEvent},

    // implements events
    events: {value: {
      "click": function (e) {
        console.log(this instanceof WhateverUIClass, e.type, e.eventPhase);
        // to remove the event, if necessary
        this.cancelEvent(e);
      }
    }}
  }
);

document.addEventListener("click", new WhateverUIClass, false);
document.addEventListener("click", new WhateverUIClass, true);


Best Regards
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20120109/4482e8ae/attachment.html>


More information about the es-discuss mailing list