Thursday, March 28, 2013

Angry Birds of JavaScript: Blue Bird - Events

Introduction


A diabolical herd of pigs stole all of the front-end architecture from an innocent flock of birds and now they want it back!

A team of special agent hero birds will attack those despicable pigs until they recover what is rightfully theirs, front-end JavaScript architecture!

Will the birds be successful in the end? Will they defeat their bacon flavored foe? Let's find out together in another nail biting episode of Angry Birds of JavaScript!

Check out the series introduction post for a list of all the birds and their attack powers.

Previous Attacks



Blue Bird Attack


In this post we will take a look at the Blue Bird who triggers events and messages that scatter to infiltrate the pig's castle. Slowly, one by one, the birds will take back what it theirs to keep!

What Was Stolen by the Pigs?

The birds used to build their web applications with components having hard dependencies on each-other. They eventually started to learn to reduce tight coupling by introducing events and messages. Unfortunately the pigs, during their invasion, stole the birds' observer secrets.

One of the blue birds has been tasked with taking back what has been stolen and restore loose coupling components.

Sample Application


In order to unpack the need for messages we will look at the following web application to search for movies from Netflix. We will uncover how this application was originally coded and then refactor along the way.



Tightly Coupled Code


The first version of the above application was coded using the following JavaScript code. Take a look at the code and let it start to sink in for a little bit. It may be painful, but please bar with me for a moment ;)


The above code sample is a typical jQuery example that you can find across the internet. The snippet works, but there is a lot of different things happening all in the same place. You can find event handling, data retrieval, and data manipulation all mixed together. You can imagine that over time this code might continue to grow and grow and become more and more prone for errors.

Before we get too far, let's take a side trip and look at what messages are and what types exist.

Types of Messages


Observer Events


An observer event is probably one that you are most used to if you are familiar with front-end web development. In relation to the DOM you can think of this as adding event handlers to an element. The element has a direct reference to the callbacks that will be invoked when the event type occurs.

Example



Mediated Events


A mediated event or message has become more common the last several years in front-end web development. The main idea here is that there is another entity that keeps track of publishing and subscribing of messages. The main difference between this and Observer events is that Mediated events aren't tied directly to the subject that invoked it.

Example



Implementations


There are several libraries out there that facilitate mediated events. The following is a list of various libraries that you may want to choose from. My recommendation is that you look at Jim's postal.js library.


Hybrid Events


There is another type of event that is sort of a hybrid between observer and mediated. This type looks like a mediated event, but if you look hard enough there you could actually trace the origin of the event back to the original subject. A good example of this is jQuery's delegated event model. Delegated events are great, but it is based on the concept of events bubbling up the DOM and therefore we can trace where it came from.

Example



By the way, I don't recommend using the $._data() method as it is undocumented and therefore not guaranteed that it will be available in future versions of jQuery. It is an internal helper method that jQuery currently uses under the covers. However, I did want to show you that there is a way to poke around and get at information that the subscriber shouldn't have in a real "mediated event", which is why I'm calling it a hybrid event. Don't get me wrong, I love jQuery's delegated events. I just wanted to show how it is a hybrid of the two above concepts.

Which One Should Be Used?


That information is all fine and good, but what type of event/message should you be using and when? That is a great question and one that my friend Jim addressed in a recent post that he wrote. The following is a quote from his article...

"...use observer 'locally', inside a component, mediator 'remotely' between components. No matter what, be ready to use both in tandem.' --Jim Cowart

Jim recommends using observer events (jQuery's .on() method) when communicating within a module and to use mediated events (postal.js) when communicating between modules.

Another technique that Jim brings up in his article is to promote observer events into mediated events, which gives you the both of both worlds. He has some nice examples showing how that could look. I encourage you to take a look at his article referenced below in bold.

Additional Resources


If you are interesting in more information about the above concepts you may consider looking through some of the following resources about events and messaging.


Loosely Coupled Code


I was tempted to write the following code using Backbone.js or create constructor functions, but in order to keep it simple and convey the idea of messaging I tried to remove all of that. So, this probably isn't what you'd have in your code-base, but hopefully it gets the point across.


Attack!


The following is a simple Angry Birds clone using boxbox, a framework for the box2dweb JavaScript physics library, written by Bocoup's Greg Smith.

Press the space bar to launch the Red Bird and you can also use the arrow keys. If it takes you too long to destroy the pigs you might want to consider pressing the space bar several times ;)



Conclusion


Using events and messages across your web application can help with communication. Events allow a component to communicate with itself and messages can enable other components to listen in without having a hard dependency.

There are many other front-end architecture techniques that have been stolen by the pigs. Tune in next time as the next Angry Bird takes its revenge! Dun, dun, daaaaaaa!

Monday, March 25, 2013

Angry Birds of JavaScript: Red Bird - IIFE

Introduction


A diabolical herd of pigs stole all of the front-end architecture from an innocent flock of birds and now they want it back! A team of special agent hero birds will attack those despicable pigs until they recover what is rightfully theirs, front-end JavaScript architecture!

In this post we will take a look at the Red Bird who attacks with the force of their trusty IIFE, the basic block of all privacy.

What Was Stolen by the Pigs?


For ages the birds used to litter the global namespace (the window object) with their custom objects and functions. Over time the birds slowly learned techniques to protect their objects from the global namespace, however, since the recent pig invasion all of their anti-global secrets have been stolen! Thankfully the birds are fortunate that a one foul exists with the knowledge of this secret and plans to attack the pigs to unleash what is rightfully theirs.

How Objects Become Global?


There are several ways that an object can become global. Part of the battle is just knowing the various ways.

1. Declaring an Object in the Window Scope

In the following example there two variables declared, type and attack. These variables were declared in the top level scope and therefore are accessible off of the window object.


2. Not Declaring an Object in Any Scope

One of the most dangerous and easiest things to do in JavaScript is to accidentally declare a global variable when you didn't mean to. If you forget to declare a variable then JavaScript declares it for you as a global! This is usually not what you meant to do and could expose parts of your application that you didn't intend.


3. Specifically Adding an Object to the Window

You also have the opportunity to expose variables to the global namespace intentionally. You can easily do this by accessing the window object and adding a property or method manually. It isn't a good idea to use this technique deep inside your code, but it is worth nothing that you can.


Why Are Global Objects a Problem?


  • Conflicts within Your Code

    There is a risk that developers within your own company may define the same function, method, or property that already exists in your application. If you have no mechanism to reduce the number of items in the global namespace your risk of accidentally reassigning a variable grows as your application gets larger and more complex.

    You may dismiss this reason because you have rigid code reviews and all your developers know your codebase inside out. If that describes you, then check out the next reason ;)

  • Conflicts with Your Code and Third-Party Libraries

    Another danger of having multiple global objects is that your code could conflict with third-party libraries that you are using. There are a lot of libraries, plugins, and frameworks out there and not all of them are as aware and conscious about keeping their global variables to a minimum. Your code and the libraries you include could clash and override each-other's behavior which can cause unexpected results.

    You may dismiss this reason because you deeply scrutinize all third-party libraries that your team uses and are fully aware of what global variables are exposed by these libraries. If that describes you, then check out the next reason :)

  • Conflicts with Your Code and Browser Add-ons/Extensions/Plugins

    The final danger of having multiple global objects is that your code could conflict with the browser itself. What!?! Lets take Google Chrome for an example. Chrome's add-ons are JavaScript based and all of your installed add-ons run on your web page when it is loaded. You never know what add-ons your users have installed and as a result there is a risk that those add-ons will expose global variables that conflict with your code-base.

    Does this seem far-fetched? Well, it can at first, but I've actually seen a high profile website (not going to mention which one) run into this very problem. I was trying to use the website and it was broken. I knew the developer so I reached out to him. After some back and forth it turned out I had an add-on installed that broke the website. I contacted the add-on author and they updated their code and now all is fine.

Various Ways to Protect Yourself


Although the above code snippets were very small and simple, they all exposed way too many variables to the global namespace. So, how do we protect ourselves?

  • Object Literal

    The easiest way to help prevent global variable proliferation is to protect yourself with an object literal that limits gathers all objects that would have been global and attaches them to once central object.


  • Immediately Invoked Function Expression

    The Immediately Invoked Function Expression (IIFE) is another technique to get around the global issue. This technique is more complicated than the Object Literal, but provides much more power as well. This technique allows the developer to expose public and private properties and methods to the consumer.

    Before we get into what this looks like, lets work through some of their weird syntax that we are about to see. The scoping of variables in JavaScript is determined via the function scope and not block scope. So, if you have a variable declared inside an if statement for example it would be available everywhere inside its containing function. This might seem a little jarring to some developers that are used to C, C++, C#, Java, or similar languages.

    So, we are going to use this functional scope idea to create an anonymous function (function with no name) and immediately invoke it.


    Unfortunately, the above snippet doesn't work in JavaScript because it can't parse it correctly. The idea is solid, but the implementation is off just a little bit. Thankfully, there is an easy way to let JavaScript know that we know what we are doing and that is to surround the expression with an extra set of parenthesis.


    The following pattern is known as the Revealing Module Pattern. You should notice the use of the IIFE to create the special functional scope and the note-worthy part is the end where you return the parts of the scope that you want to be public to object and anything not returned will be private.


    You may also run across this alternate syntax that is popular in many libraries and frameworks. The pattern uses the IIFE, but this one passes in the global variable to use as a namespace. The window.bird = window.bird || {} code snippet is a fancy way to check if the bird object already exists and if it doesn't then to create a new one. Whatever gets added to the object from within the IIFE becomes public and whatever memory isn't attached to the object stays private. The nice thing about this pattern is that it can be repeated and build up a library with various components.


Attack!


The following is a simple Angry Birds clone using boxbox, a framework for the box2dweb JavaScript physics library, written by Bocoup's Greg Smith.

Press the space bar to launch the Red Bird and you can also use the arrow keys.


Conclusion


These techniques are vital for a front-end application so that it can protect itself from other code and it also gives the opportunity to structure your code in a way that is encapsulated from its surroundings.

There are many other frotn-end architecture techniques that have been stolen by the pigs. Tune in next time as the next Angry Bird takes its revenge! Dun, dun, daaaaaaa!

Angry Birds of JavaScript Series


Introduction


A diabolical herd of pigs stole all of the front-end architecture from an innocent flock of birds and now they want it back! A team of special agent hero birds will attack those despicable pigs until they recover what is rightfully theirs, front-end JavaScript architecture!

Meet the Special Agent Hero Birds


Over the course of the next several weeks you'll be introduced to the following team of super hero birds...


Red Bird


The Red bird attacks with the force of their trusty IIFE, the basic block of all privacy.

Status: Published


Blue Bird


The Blue Bird triggers events and messages that scatter to infiltrate the pig's castle.

Status: Published


Yellow Bird


The Yellow Bird comes with a RequireJS speed booster and dynamically injects scripts against those pesky swine.

Status: Published


Black Bird


The Black Bird proves to be a much more organized approach to fighting these porkers and introduces the Backbone.js bomb to their dismay.

Status: Published


White Bird


The White Bird appears to be seemingly harmless, but when it pulls out it's strict coding style and bursts of quality checks the hogs are sure to squeal.

Status: Published


Green Bird


The Green Bird can reach all of those hard to reach places and will mock and spy those stealing swine right where it hurts!

Status: Published


Orange Bird


The Orange Bird starts out small with a simple template, but then expands itself into a DOM blast that will surely send the message that the birds mean business.

Status: Published


Big Brother


The Big Brother pulls out the big guns with his finite state machine and other proven design patterns of destruction.

Status: Published


Mighty Eagle


The Mightly Eagle uses the most superior weapon of them all, a suite of tools that can organize and deploy all the other birds into battle against their soon to be vanquished foe.

Status: Published



Images provided via Angry Birds Wiki

Conclusion


The above series will be presented at the upcoming <anglebrackets /> and FluentConf conferences and possibly others. I hope you enjoy the series. I am having fun putting it together and I look forward to giving it in front of an audience ;)

Wednesday, March 20, 2013

New Beginnings

Introduction


Today is my last day at appendTo, LLC. I've been working with appendTo for over 2.5 years and have been doing a combination of architecture reviews, project work, staff augmentation, and preforming on-site and virtual remote trainings.

I've learned a lot while at appendTo. I've grown in my confidence as a developer and a trainer and I've valued working alongside talented developers and friends. I appreciate the time I've been at appendTo, but it is time to move on.

Going Out On My Own


I've decided to go out on my own and start my own business! This day comes with a mixed bag full of emotions. My company name is Manorism, Inc. I've purchased the manorism.net domain (haven't launched it yet) and hope to acquire the .com from its current owner.

My company will primarily center around training. My initial focus will involve creating several PluralSight videos and then I hope to branch out to do remote/on-site trainings, workshops at conferences, and some consulting on the side. I start on my 1st PluralSight course starting tomorrow and it should be available in about a month.

I'm not going anywhere and if anything else you should see more of me than you have previously ;) Again, thanks appendTo and keep your eyes open for Manorism, Inc.

Monday, March 11, 2013

<anglebrackets /> Front-End Web Conference

A new front-end developer conference is starting in Las Vegas April 8-11! This conference will be focusing primarily on the front-end concerns such as HTML5, CSS3, and JavaScript.

This event reminds me a lot of the Microsoft MIX conferences that used to be held for the last several years. I am glad to see something like this conference come to fruition and I'm honored to be one of the speakers chosen for its 1st meeting.

In addition, this conference will be taking place in-tandem with another conference called Dev Intersection & SQL Intersection. This other conference will be more focused on Microsoft and .NET technologies. These two conferences will be held at the time and location so you can hop between the conferences as you wish.

If you are interested in attending either of the conferences you can use the "MANOR" discount code for $50 off your <anglebrackets /> Registration OR Dev Intersection & SQL Intersection Registration price.

Speakers


At the <anglebrackets /> conference I'll be speaking alongside many well known speaker such as

  • Scott Allen
  • Todd Anglin
  • Justin Beckwith
  • Miguel Castro
  • Jim Cowart
  • Damian Edwards
  • Jason Follas
  • Brady Gaster
  • Phil Haack
  • Scott Hanselman
  • Christian Hellmann
  • Burke Holland
  • Billy Hollis
  • Scott Hunter
  • Denise Jacobs
  • Brian Noyes 
  • John Papa
  • Jonathan Snook
  • Lea Verou
  • Dan Wahlin

Sessions


Some of the sessions that look interesting to me are...

  • 5 Tips for Better JavaScript
  • ASP.NET - Don't Do THAT! Common Mistakes and Pitfalls
  • Break Out Of The Browser With HTML5
  • Comparing JavaScript Frameworks: Ember, Angular, and Knockout
  • Eventing and Messaging in JavaScript
  • Getting Started With Require.js
  • HTML5 for Business: Forms and Input Validation
  • Modern Single Page Applications with  HTML5, CSS3, JS, ASP.NET and Visual Studio
  • etc...

I will be presenting the following two sessions at the event


See You There!


It should be a fun event and I hope to see you there. There are also some nice workshops you might want to check out. If you are able to make it then come up after one of my talks or stop me somewhere, I'd enjoy getting to meet you.

Remember the "MANOR" discount code for $50 off your <anglebrackets /> Registration OR Dev Intersection & SQL Intersection Registration price.