Zombie Events, How To Kill Them And How To Avoid Them

zombies21If you do any kind of front-end development I’d say that eventually you had run into Zombie events. If you haven’t then let me explain what they are:

Zombie events are events that are raised for elements that have been removed from the DOM and they are the result of using event delegation for event handlers.

Simply put, event delegation is the practice of attaching event handlers to DOM elements that are parents to the actual DOM elements raising the events (the event targets) as opposed to the practice of attaching event handlers directly onto the DOM elements that actually raise the events (the event targets).

Event Delegation – An Example

As an example, suppose we have a list of links. Instead of attaching a click event handler to each li element we instead attach all of the click event handlers to a parent tag of the li elements, the ul tag, or to a div element serving as a container, or even to the body element itself. That is, in a nutshell, what event delegation is.

First, the markup

<div id="page_container">
    <ul>
        <li><a href='#'><span class='somelist'>some text</span></a></li>
        <li><a href='#'><span class='somelist'>some text</span></a></li>
        <li><a href='#'><span class='somelist'>some text</span></a></li>
    </ul>
</div>

and then the JavaScript

(function ( window, $ ) {
    'use strict';
    $( function () {
        $( '#page_container' ).on( 'click', function ( event ) {
            // we only are interested in the event if it was raised by a span element with a class of 'somelist'
            var $eventTarget = $( event.target );
            if ( $eventTarget.attr( 'class' ) === 'somelist' ) {
                window.alert( $eventTarget.attr( 'class' ) );
            }
        } );
    } );
}( window, jQuery ));

In the example markup above, a list is created consisting of 3 anchor tages, each of which has a span tag with a class of ‘sometext’ and in the JavaScript example code above, all click events are delegated to the div whose id is ‘page_container’. When the click event is raised, it will bubble up the DOM and when it reaches the parent container with an id of ‘page_container’ the event callback function will be called. In the event callback function, since we are only concerned with click events that were raised by span elements with a class of ‘sometext’, we filter for only those related events and ignore those that aren’t.

The Advantage Of Using Event Delegation

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time which would be a commaon need in dynamic pages, specifically single page applications, where dom elements are added to and removed in response to the user’s interaction with the page.

The Disadvantage Of Using Event Delegation Are Zombie Events

While the benefits of using event delegation far outweigh its disadvantages, you do have to insure that when elements are removed from the page that any delegated events associated with those elements are removed as well. If these aren’t removed then the result will be Zombie events.

Avoiding Zombie Events & Killing Them If You Have Them

To kill Zombie events you first have to know how they are created. Once you understand that, getting rid of the little buggers is easy. If you’d like to learn all about Zombie events, how they are created and how you can eliminate them, then I suggest you head on over to my repo on GitHub where you can do just that!

And That’s A Wrap!

As always, feel free to leave comments and feedback. I always enjoy hearing from you.

:q

How You Create Your Objects Does Matter, But Maybe Not Why You Think

index.html pageJavaScript (ES5) can accommodate constructing objects and object hierarchies using pseudo classical, prototypal and composition/modular. I’ve often wondered what the ramifications are in terms of browser performance and resources these methods have. In order to find out, I created a simple hierarchy consisting of a person and an employee with person being at the root of the hierarchy and employee inheriting from person. I then modeled this hierarchy using each of the 3 methods, ran each of the methods through a benchmark that consisted of creating 1,000,000 object instances and recorded the time to completion.

My expectations before actually running the benchmarks were that of the 3 methods, pseudo classical would be the fastest, followed by composition and then last but not least, prototypal. My reasoning for my assumptions were:

  1. Pseudo classical should be the fastest because ‘new’ is baked into JavaScript and so I imagined that every JavaScript virtual machine should optimize the crap out of it. Secondly, pseudo classical doesn’t need to copy ‘hasown’ properties as prototypal does (see the source code of my implementations on GitHub).
  2. Prototypal should be the slowest because 2 objects are needed to create an instance, the prototype to base the new object on and a second object which must be iterated over and whose ‘hasown’ properties are copied to the new object.
  3. And finally composition, which I just assumed would always fall somewhere in the middle of the others.

The benchmark tests I created do not use the DOM at all, they merely create the intended object and they do not store them in memory. My goal was to create these tests so that they would be similar to putting a car on a dynamo, putting the transmission into neutral, and flooring the gas pedal.

Creating 1,000,000 Objects – The Benchmark Results

I was kind of surprised, actually, at the results. Not only were my assumptions not always right but it is clear that the 3 browsers that I tested on my Mac (all the latest versions of Chrome, Safari and Firefox as of February 27, 2013) are not all created equally when it comes to creating lots of objects… Not even by a long shot.

chrome browser console

Chrome Browser Console Output

firefox browser console

Firefox Browser Console Output

safari browser console

Safari Browser Console Output

When Speed Counts, Think About How You Approach Object Creation

What is clear from my test results, though, is that Chrome’s virtual machine is by far and away the fastest of the 3 browsers when asked to create millions of objects. On average I’ve found that  when using pseudo classical/new, in fact, it is almost 60 times faster when compared to Safari and almost 28 times faster when compared to Firefox. Things start to even out somewhat when using prototypal, but when it comes to using composition, Chrome once again blows the doors off the others being almost 10 times faster.

As my test have shown, if you are creating millions of objects as my tests did then you need to think about your approach and if time is really critical then maybe you should consider targeting each browser with a specific approach.

Get It On GitHub And Run The Tests 

My repo on GitHub contains all the code I used to test. There are no other dependencies. I also included a nice little web page for initiating the tests and displaying the output though in order to view nanosecond based results you will have to view the results in the browser console.

I’m looking forward to hearing from you all, especially I’m interested in your reactions to the test results and even about the code that I wrote for benchmarking. Please feel free to leave your comments here.

Oh, one last note – I didn’t run these test on Windows or Linux so if someone would like to do that and comment on your finding here then that would be greatly appreciated. I am very curious regarding the effect that the OS has on the test results and the results for the latest versions of IE.

:q

Prototypal versus Pseudo Classical – The Debate

ImageDisplay_im

In JavaScript circles there can be no greater contentious debate than the one revolving around prototypal versus pseudo classical inheritance and cantankerous discussions about politics can appear civil when compared. Proponents on either side of the aisle are quick to deride those whose views differ from their own. The ‘purists’ as I call them are quick to point out that there are no classes in JavaScript and that objects beget objects, period! On the other hand, ‘classical style’ developers (those who very likely came to JavaScript after having used a traditional class based programming language, such as C++, Java, C#, et al.) are quick to point out that JavaScript actually does support object creation via its new operator conjoined with constructor functions which provides the semantic sugar needed to mimic traditional class- based languages.

Part of the problem, I believe, lies in the terms either side use to bolster their own views. For instance, when speaking on the subject proponents on both sides of the debate often refer to ‘classical inheritance’ instead of the using the correct term which is ‘pseudo classical inheritance’. In this regard I believe even Douglas Crockford refers to the conjoined use of the new operator with a constructor function as pseudo classical inheritance and not as classical inheritance. Inclusion of the word pseudo here dramatically changes the meaning and obviates any confustion that it isn’t really classical at all but rather is a fake or pretending form of classical inheritance.

Furthering the confusion is the often misquoting of Douglas Crockford on this subject. While Mr. Crockford classifies the conjoined use of the new operator with a constructor function as one of JavaScript’s bad parts, it is important to understand his motivation for that. JavaScript at this time (here I am referring to Ecmascript 5) cannot prevent you from calling a constructor function without the use of the new operator. This can result in polluting the global name space. Knowing this then should reminds us all that we should be using static parsers such as JSLint and JSHint and declaring ‘use static’ in all our functions.

So what, then, is the real issue here and why do I really not care that much about it? There are certain developers who are passionately opinionated on this subject and they feel they must try to coerce everyone into accepting their own opinions as the gospel and heaven help you or anyone who disagrees with them. In development as in life we can not escape the fact that there will always be those who want to draw us in to their own views of correctness, so beware.

JavaScript is an incredibly expressive and dynamic language. It allows us to create objects in many different ways and I believe that is one of JavaScript’s greatest strengths. It is therefore a testament to the versatility of JavaScript that the language allows those who favor one form of object creation over the other to use their favored approach.

When coding JavaScript I use both pseudo and prototypal approaches to creating objects though I admittedly favor shallow object hierarchies and composition(*1) over deeply rooted inheritance. Mr. Crockford seems to favor this technique as well. In its essence, composition allows avoiding deeply rooted object hierarchies while allowing for the ability to create semantically rich and expressive objects. JavaScript makes implementing composition incredibly easy and I will cover composition in depth in a future article.

The best advice I can give to budding JavaScript developers is the following:

  • Avoid getting caught up in philosophical debates. That isn’t to say you shouldn’t have opinions. Just don’t get caught up in them. Instead focus on perfecting your craft and code, code, code.
  • Learn how to create objects using all the varied ways that JavaScript supports — prototypal, pseudo classical and composition.
  • Understand their good and bad parts — they have both.
  • Use linting all the time. Today there is no excuse for not using it. If your editor or IDE doesn’t support real time linting then dump it and find one that does.
  • Use strict. Unless you are dealing with legacy code any new code you develop should include ‘use strict’ in every function.
  • Last but not least, let your own educated opinions guide you – emphasis on ‘educated’.

(*1) To be more precise, I often create objects combining prototypal inheritance, the modular pattern and composition.

:q

A Much Better Way To Do Callbacks

$.Deferred and Promise

The traditional way of dealing with callbacks in JavaScript can often yield unreadable and hard to maintain code. jQuery’s Deferred ($.Deferred), a chainable utility object first introduced in v1.5, can be used to register multiple callbacks into callback queues, invoke callback queues, and relay the success or failure state of any synchronous or asynchronous function. Using $.Deferred and Promise can eliminate many of the negatives often associated with cascading callback functions.

Rather than writing a full tutorial I thought it would be better to provide you with real working examples using $.Deferred and Promise which cover various use cases. The code in my repo is well documented and simple working code that you can clone from GitHub at github.com/jeffschwartz/jQueryDeferred and explore on your own using just your browser and a simple code editor.

If you have not yet been exposed to $.Deferred and Promise I recommend you read the 2 articles I mention below as well as jQuery’s own documentation, located at http://api.jquery.com/category/deferred-object/. These 3 resources should provide you with a solid foundation and understanding of $.Deferred and Promise which will make following my code much easier.

  1. The article by Jeremy Chone, at http://www.html5rocks.com/en/tutorials/async/deferred/
  2. The article by Julian Aubourg and Addy Osmani, at http://msdn.microsoft.com/en-us/magazine/gg723713.aspx

Includes 4 Examples and a Test Suite

The code comes with 4 examples covering 4 use cases, which are:

  1. Example #1 – calling getData1 to obtain an integer using Promise.done & Promise.fail
  2. Example #2 – calling getData2 to obtain an integer using $.when and Promise.then
  3. Example #3 – calling getData3, getData4 in parallel to obtain 2 integers using $.when and then summing the 2 returned integer values using Promise.done
  4. Example #4 – calling getData5, getData6 in parallel to obtain 2 integers using $.when and then calling getSum using Promise.then to sum the 2 returned integer values and obtaining the result using Promise.done

In addition to the 4 examples, a full test suite that includes 7 tests, one for each mock api function, is also included and it uses QUnit. To run the tests open the test/qunit.html file in your browser.

Comments are appreciated as always.

:q

Under The Hood

I’m naturally curious. That is why I read and study so much and it is also why I am passionate about programming. When I’m working with a new library I’m constantly asking myself “how’s it doing that?”, and so I spend a lot of time looking under the hood, so to speak.

This article is all about me looking under the hood and reporting what I find there. This isn’t going to be a static document. I’ll keep appending new things to it as I learn rather than writing new articles for each, and so it is not a one time deal and you will need to check back here every once in a while if you are at all curious to find out what’s the newest thing I’ve discovered and what my ‘take away’ from it is.

Node Uses Both Prototypal and Pseudo Classical Styles – published 20012/10/27

In an Express.js based Node application, you typically see the following boilerplate code in app.js:

http.createServer(app).listen(app.get('port'), function(){
  console.log("Express server listening on port " + app.get('port'));
});

As tempting as it may be to just take it for granted that the code above sets up the listener for requests arriving on the specified port, I decided to dig a little deeper into the source code and perhaps learn a thing or two. What follows are some of the little tidbits of goodness that I’ve been able to spy.

From the boilerplate code above, for instance, the reference that createServer returns points to an instance of a Server object whose own prototype is inherited from net.Server’s prototype. How’s it doing that? To be able to answer that we have to look under the hood of the http module (http.js), beginning with its createServer method.

function Server(requestListener) {
  if (!(this instanceof Server)) return new Server(requestListener);
  net.Server.call(this, { allowHalfOpen: true });

  if (requestListener) {
    this.addListener('request', requestListener);
  }

  // Similar option to this. Too lazy to write my own docs.
  // http://www.squid-cache.org/Doc/config/half_closed_clients/
  // http://wiki.squid-cache.org/SquidFaq/InnerWorkings#What_is_a_half-closed_filedescriptor.3F
  this.httpAllowHalfOpen = false;

  this.addListener('connection', connectionListener);
}
util.inherits(Server, net.Server);

exports.Server = Server;

exports.createServer = function(requestListener) {
  return new Server(requestListener);
};

See the call to util.inherits(Server, net.Server) on line 16 above? Here’s the code from the util module (util.js) and guess what it is doing:

exports.inherits = function(ctor, superCtor) {
  ctor.super_ = superCtor;
  ctor.prototype = Object.create(superCtor.prototype, {
    constructor: {
      value: ctor,
      enumerable: false,
      writable: true,
      configurable: true
    }
  });
};

On line 3 above we see that the method inherits is calling the Object.create method, passing it a reference to net.Server’s prototype. The object reference that Object.create returns is an object whose own prototype inherits from net.Server’s prototype, and that reference is assigned to http.Server’s prototype property. So though htttp.Server doesn’t itself have a listen method, it inherits one now prototypically. If you are still confused, just think of net.Server’s prototype serving as http’s super prototype. I was going to say its superclass but I don’t want to confuse you even more than you might already be.

And the takeaway of this is

For me what’s worth noting here is that Node’s modules use both prototypal style and pseudo classical style in a  complimentary manner, thereby producing a utility whose sum is greater than what using either one alone might provide. This confirms to me, at least, that I should no longer have to pick one way or the other of modeling object hierarchies in JavaScript and that instead I should be thinking in more dynamic terms of using both styles, just as the code in Node’s modules are.

:q

A Childhood Favorite — Tic Tac Toe

I’ve always wanted to recreate the simple games of my youth on the computer. Those games, the ones I played with pencil and paper and loved as a child, were as exciting to me then as the video games must be to the children playing them today.

So here’s Tic Tac Toe, which I chose to be the first game I’d recreate because out of all the childhood games of my youth none were as exciting and as much fun to play. The funny thing is, I still enjoy playing it today, and now, having written this, I won’t even need pencil and paper anymore. I don’t know if that’s a good or a bad thing but I do know I had a real blast cooking this game up.

So click on the link above and play a few games of Tic Tac Toe and see who’s really smarter, you or the computer.

I wrote Tic Tac Toe using 100% JavaScript. That means JavaScript on the server and JavaScript on the client. Here’s a few implementation details, just in case you are interested:

On the front end I employed:

  • A customized version of Twitter Bootstrap’s 12 column grid. I needed to eliminate the gutters between columns so the divs could buttress each other which was necessary for the game grid.
  • RequireJS for JavaScript modularity.
  • LESS for dynamic CSS stylesheets.
  •  JavaScript/jQuery for the Tic Tac Toe game engine. Nothing fancy here but I did intentionally dumb down the computer somewhat because I didn’t want it to be too one-sided in the computer’s favor. You can win if you are careful but I have to admit, the computer is pretty smart too ;)

And on the back end I used:

  • NodeJS for the http server.
  • Express Web Framework for simple http request routing.
  • EJS for dynamic embedded JavaScript HTML generation.
  • MongoDB for storing unique url hits and from which a visitor count is displayed in the footer of the page.
  • MongoSkin for its nice MongoDb wrapper employing the future pattern.

The source code for Tic Tac Toe is available on GitHub.

So that’s a wrap… Tic Tac Toe, anyone?

:q

The Tools Of My Trade – WebStorm

I think it is a good idea to take stock of my tools every so often, to make sure they are in line with what I am trying to accomplish and aren’t themselves limiting me. Of all the tools in my tool box the most important to me are my IDE and code editor. Today, I’d like to focus on my IDE of choice.

WebStorm, the dedicated JavaScript Web development IDE from the good folks over at JetBrains, is a phenomenal JavaScript Web development environment and I’ve been champing at the bit wanting to write a raving review for a while now. Unfortunately I haven’t had the time to do an in depth review, so instead I will take a different approach and focus on only those features that in my opinion set WebStorm apart from its competition. I will also touch upon a few of its weaknesses that I would like to see addressed as well.

Where WebStorm Rocks:

1) Speed – My primary development tool has to be fast and anything less just wont cut it. WebStorm is the fastest IDE I’ve every worked with. It is quick to boot up and once booted it remains snappy. Project indexing which is often responsible for bringing an IDE to its knees is fast and I have never incurred any latency during the process.

2) Configurability – The folks over at JetBrains obviously recognize that we developers are a very picky and demanding bunch and that we will quickly reject any tool that doesn’t allow us to configure it to our specific likes, needs and work flow requirements. So not only did they provide us with a huge number of configuration options but they also made it very easy and accessible. From within configuration you can enter search criteria and WebStorm will return a list of configuration items that match your search criteria. Now that’s what I call a really smart approach to simplifying configuration.

3) The Editor Is My Canvas - The editor is where I often find myself in 8, 10, 12 or more hours a day. The quality or lack of it will either make or break a product for me. After all, I write code — that’s what I do. Writing code is my passion and the way I earn a living — and as such I demand more from my editor than from any other tool that I work with. My editor has to allow me to get as much work done without exiting out to some other application or tool which would just break my work flow and my concentration and that’s not a good thing. The way I see it, an artist never has to leave their canvas to paint and so a developer should never have to leave their editor to develop. WebStorm’s editor is my canvas.

4) Key Bindings and Keyboard Shortcuts – I’m a huge fan of VIM. I like VIM’s modal approach to editing. VIM allows me to be more productive because I rarely have to take my hands off of the keyboard and reach for my mouse or trackpad, which are actions that when repeated often can be distracting and physically challenging over the course of a long day.

WebStorm’s VIM key bindings duplicate many of VIM’s keyboard commands and though not a “hard core VIM” experience, it does provide enough of one and it works extremely well. Honestly, if it hadn’t I’d have rejected WebStorm outright which just goes to show you how serious I am about this.

In conjunction with good VIM support, WebStorm provides access to almost all of its features through handy keyboard shortcuts, which when used together with the VIM key bindings makes the physical act of typing in WebStorm quite productive and pleasant.

5) GIT Support – In a word, fantastic! Branching and shelving are well supported as is cloning from and pushing to github. I especially appreciate that WebStorm supports github Gists which I use as a repo for my code snippets.

6) Pretty and Nearly Distraction Free – Yeah, I said pretty. It shouldn’t seem odd that I would expect the environment I’m working in all day long to be visually appealing. Ugly is distracting and ultimately will affect my creativity and productivity. Therefore ugly is out. By using an assortment of WebStorm configurations I’m able to tailor WebStorm to be pretty and distraction free, eliminating most of its user interface. That’s how I like it!

7) Plugins - WebStorm is extensible through its plugin system. In fact, many of WebStorms features are provided through plugins. There are also numerous 3rd party plugins available as well. My favorite plugin is AceJump, written by John Lindquist, and the best description I can give it is that it is like search on steroids.

8) Live Templates - Live Templates are to WebStrorm as Snippets are to TextMate. They allow you to easily extend and add features to the editor.

9) Frequent Updates and Bug Fixes – I’ve already received one major update and 2 minor updates. It’s obvious to me that JetBrains stands behind their tools.

10) Server and Client Side Debugging – Easily debug server side and client side JavaScript. Really handy for both server side Node development as well as for front-end development.

Some Improvement Needed: 

This is my short list of those items I would most like to see addressed in future releases of WebStorm. WebStorm is a broad product, it attempts to do many things very well and for the most part it does. In my opinion it doe so better than any other IDE in its category. However, as excellent as WebStorm is there is room for some improvement. So here’s a few of my top wish list items:

1) Plug a few gaps in the VIM key bindings – As good as WebStorm’s VIM key binding are, it is missing a few that I think it should have. Most notably it doesn’t implement the character case switching commands in full. Complete support for this group of VIM keyboard commands is important when writing code in programming languages that are case sensitive as is the case (no pun intended) with JavaScript.

2) Improve Code Completion – Code completion is still too often a hit and miss proposition, even with the inclusion of external libraries, and while I understand this is really hard to do with dynamic languages such as with JavaScript I am hoping that JetBrains can improve on this.

3) Provide Custom Scaffolding Templates - I need a way to describe to WebStorm how to generate projects. I want to define the files, libraries and their versions that I want WebStorm to include as well as the actual structure of the project itself, including the names of the folders. I should be able to include files that reside either on the web or locally. Sounds or feels like something along the lines of a package manager to me but in any case it would allow me to pick and chose the libraries and files I want to use along with their versions. Perhaps just integrating with NPM or one of the other popular package managers would provide what I’m looking for. Maybe not an easy thing to do but it can’t hurt to ask, right?

4) Debug Both The Back and Front Ends At The Same Time - Right now you can debug one or the other but not both at the same time. Well, at least I haven’t been able to get this to work. So when working with Node it would be extremely handy and a real productivity booster if WebStorm were able to debug both at the same time.

Conclusion:

While there are numerous free and open source options available, in the end I chose to purchase a license for WebStorm because none of the other options appeared to me to be as feature rich and as refined as WebStorm is. The attention to detail in this product is excellent and the 49 bucks US I paid for WebStorm is in my opinion an incredible value, especially considering how much utility it provides me and how productive I am with it.

As far as JavaScript development is concerned, WebStorm sets the bar to which all other dedicated JavaScript Web development IDEs must be measured against. Kudos to JetBrains for producing the finest dedicated JavaScript Web development IDE I’ve had the pleasure of using.

Links To References:

WebStormhttp://www.jetbrains.com/webstorm/.
Vim’s case switching commands - http://vim.wikia.com/wiki/Switching_case_of_characters.
AceJump plugin by John Lindquist – download directly through WebStorm’s plugin system.  Informative video available at http://www.youtube.com/watch?v=yK8eM50DsAY.

:q