Creating your own JavaScript Library – part 2 – Event Handling

Share on Facebook0Share on Reddit0Tweet about this on TwitterShare on Google+0

write-your-own-javascript-libraryIn Part 1 of Creating your own JavaScript library, we cover the library essentials: library design, creating a solid object constructor, and adding functions by extending the object prototype. This post focuses on extending our basic library with event handling.

Out of the box event handling can be accessed  through Javascript and DOM apis, shown in the first 3 examples:

Simple event handling:

Assigning functions to events this way can be problematic, as only one function can be assigned at any given time. Mozilla Developer Network recommends that the addEventListener method be used instead, because of its flexibility.

Better Event handling

The addEventListener method accepts three parameters:

Assigning an anonymous function:

We can easily wrap this built in functionality with our library by creating a click function with a parameter that is passed to this native DOM event. This parameter will be an anonymous function (like the previous example) that will then bound to the element’s handler.

Handler wrapped by our library:

This pattern can be applied to any event natively exposed, such as:

  • onclick
  • onmouseover
  • blur
  • keydown

Non-standard or browser specific events

In the case where one browsers event api differs, it is simple to account for this in our event handler:

Optimizing our code

Instead of duplicating the addEventListener code in each event wrapper, we can optimize by creating an internal addListener(event, callback) function which will be called by other exposed functions, such as click, onMouseOver, etc

This separates the public wrapper from the internal event binding, allowing us to easily modify or expand the actual event binding code without modifying it in numerous places


Share on Facebook0Share on Reddit0Tweet about this on TwitterShare on Google+0
  • To be honest I’d use DOM events (addEventListener and friends) rather than the old Netscape-style events, otherwise you’ll have people complaining about their event listeners going missing 😛

    I don’t think the old-school ones handle bubbling either (I could be wrong here).

    • mdjasper

      You know? you’re completely right. I initially used “old school” events for the purpose of simplicity in the tutorial. But after some thought, I think its better to teach it right the first time.

      I’ve updated this post to reflect your feedback. Thanks.