Thursday, April 11, 2013

Angry Birds of JavaScript: Mighty Eagle - Automation

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


Mighty Eagle Bird Attacks


In this post we will take a look at the Mightly Eagle who 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. Slowly, one by one, the birds will take back what it theirs to keep!

What Was Stolen by the Pigs?


Over time the birds picked up RequireJS (Yellow Bird), JSHint (White Bird), Plato, Mustache (Orange Bird), and a bunch of other great tools, but all of them required a command line task to complete. It was getting quite annoying having to remember what was required to run each of these tools. In addition, it was easy to forget to run the tools to update their web application when necessary. Thankfully one day the Mighty Eagle introduced some tools to make things a little bit easier. The Eagle brought Grunt and Bowser to automate common tasks and to help easily bring in commonly used libraries that were necessary to e their applications.

However, during a recent invasion the pigs stole all the birds' automation tools! As a result, one of the Mighty Eagles has been tasked to reclaim what has been stolen. He will use the mighty power of the Eagle to bring together all of the helpful techniques we've seen in this series.

Grunt


Grunt is a task-based command line tool that is written in JavaScript and helps automate the build of your front-end application. The community has really grabbed on to this tool and as a result there are tons of plugins that you can choose from to automate things like CoffeeScript, handlebars precompilation, less support, JSHint checking, etc...

Several really large projects already use Grunt to assist their builds and other automation tasks such as Twitter, jQuery, Modernizr, Sauce Labs, and others.

Getting Started


In order to get started you just need to install grunt from node with the following command...


Once you've installed grunt you'll need 2 main things for each of your projects
  1. Gruntfile.js
  2. package.json

Gruntfile.js


You can create your own Gruntfile.js from scratch, you can copy a starter Gruntfile.js from the documentation, or there is a use a grunt-init gruntfile project scaffold. To install the scaffold follow the instructions from Grunt's Project Scaffolding page. The following Gruntfile.js is an example from Grunt's Get Started page...


package.json


The package.json describes your project's name, version, and any dependencies it might have such as grunt and any grunt plugins. You can copy an example package.json from the Grunt's Get Started page... (see below)


Grunt Plugins


Now that hopefully everything is setup, you can start using a whole suite of plugins to automate tasks. Here are a few interesting ones that you might enjoy...

  • grunt-contrib-coffee - Compile CoffeeScript files into JavaScript
  • grunt-contrib-compass - Compile Compass into CSS
  • grunt-contrib-concat - Concatenates files
  • grunt-contrib-connect - Starts a connect web server
  • grunt-contrib-csslint - Lints your CSS files
  • grunt-contrib-handlebars - Precompiles your Handlebar tempaltes
  • grunt-contrib-htmlmin - Minify your HTML markup
  • grunt-contrib-imagemin - Minify PNG and JPEG images
  • grunt-contrib-jshint - Validate files with JSHint
  • grunt-contrib-less - Compile LESS to CSS
  • grunt-contrib-nodeunit - Run Nodeunit unit test
  • grunt-contrib-watch - Run predefined tasks when files change
  • grunt-contrib-requirejs - Optimize RequireJS projects using r.js
  • grunt-contrib-uglify - Minify files with UglifyJS
  • grunt-contrib-yuidoc - Compile YUIDocs Documentation
  • ... more ...

jQuery's Gruntfile


I pulled down jQuery from their GitHub repository to see how they use Grunt and the following is the output when get when executing the tool.


If you look closely you'll notice they update their git submodules, build a version of jQuery from it's modules, run JSHint against the built jquery.js and tests files, creates sourcemaps, and runs a special compare file size task. If you dig deep into their Gruntfile you'll find they've also setup a custom way to run their unit tests against Browserstack, which is pretty cool if you ask me ;)

Modernizr's Gruntfile


In the same way I pulled down the Modernizr repository and typed grunt qunit to watch their 746 unit tests execute and pass in 369ms using the PhantomJS headless browser!


Grunt Resources


The intent of this post wasn't to teach you all there is to know about Grunt, but to make you aware of it if you didn't know already. It is a very nice tool to help you automatic ALL THE front-end THINGS. Check out the following resources to help you unpack how to get started...


Twitter Bower


For those of you that have used Node or Ruby you'll be familiar with npm or gems, however, there hasn't been anything like that for front-end browser scripts and styles... at least until now!

The Twitter Bower project seeks to solve that problem by providing a package manager for the web (HTML, CSS, and JavaScript).


Once you've installed bowser, then you can start downloading libraries! For example, if we wanted to pull down the latest version of jQuery we could just bower install jquery and you'll see the following...



Bower Resources


If you want to find out more about bower then I encourage you to check out some of the nice resources below.

Yeoman


The yeoman project is a scaffolding engine that works along with Grunt and Bower. You can think of yeoman as the scaffolding piece that can get your applications going quickly. In order to get started you need to install yeoman by using the following syntax...


Once yeoman is installed then you can generate a variety of different types of projects. In the following screenshot I asked yeoman to create a new webapp. It will ask me several questions along the way to tailor the application to my needs.


There are other scaffolds such as Backbone, AngularJS, etc... that you can install and get your project underway. You can view a list of more generators from the Yeoman GitHub page.

For example in the following screenshots I first create a new Backbone app and then immediately create a new bird model.




Yeoman is currently 1.0 beta and the website says there are some issues with Windows. I've been able to use it to some extend, but I'm sure there are some features that aren't yet supported, but the plan is to have it fully supported.

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 Mighty Eagle Bird and you can also use the arrow keys.


Conclusion


Embracing Grunt, Bower, and Yeoman can help automate various parts of your development, testing, and deployment process. The community for these tools are very active and you can find plugins to help cater these to your application's needs.

There is one more front-end architecture technique that has been stolen by the pigs. Tune in next time as the next Angry Bird takes its revenge! Dun, dun, daaaaaaa!

Wednesday, April 10, 2013

Angry Birds of JavaScript: Big Brother Bird - Patterns

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


Big Brother Bird Attacks


In this post we will take a look at the Big Brother Bird who pulls out the big guns with his finite state machine and other proven design patterns of destruction. Slowly, one by one, the birds will take back what it theirs to keep!

What Was Stolen by the Pigs?


The birds knew how to program for the most part, but they never had a common terminology that they all understood to represent common scenarios they kept encountering. Then one day a Big Brother Bird came along and documented a set of common Design Patterns and them names and descriptions so they could all be on the same page when talking about architecture. Big Brother Bird ended up writing these patterns in a popular piece that became known as the Gang of Foul book.

However, during a recent invasion the pigs stole the birds' Gang of Fowl book! As a result, one of the Big Brother Birds has been tasked to reclaim what has been stolen. He will use his overwhelming power of trickery to help destroy the pigs in order to take back what is theirs.

Gang of Fowl Patterns


Creational Patterns

  • Abstract Factory
  • Builder
  • Factory Method
  • Prototype
  • Singleton

Structural Patterns

  • Adapter
  • Bridge
  • Composite
  • Decorator
  • Facade
  • Flyweight
  • Proxy

Behavioral Patterns

  • Chain of Resp.
  • Command
  • Interpreter
  • Iterator
  • Mediator
  • Memento
  • Observer
  • State
  • Strategy
  • Template Method
  • Visitor

Some These Patterns in JavaScript


Singleton


The most basic form of singleton is the object literal as shown below. We are basically just creating an object and there is one of them. Technically someone could Object.create on us, but for the most part this fulfills the singleton definition. You can find a more robust solution in one of the resources recommended near the end of this post.


Factory


A factory is a way to create new objects without actually using the new keyword. The idea is that there is something abstracted away from you in the factory method. In the following example we are aren't necessarily doing anything fancy, but you could imagine that we could add some custom code down the road and the external API wouldn't change, which is the point of this pattern.


Bridge


In the following snippet of code we are creating a small bridge between an event handler and the code that will be executed. By creating a little bridge it will enabled the executed code to be tested easier since it won't have a dependency on the element context that was passed by jQuery.


Facade


A facade is common place in front-end web development since there is so much cross-browser inconsistencies. A facade brings a common API to something that could vary under the covers. In the following snippet we abstract the addEventListener logic for various browser implementations.


Adapter


An adapter is a nice way to massage one piece of code to work with another piece of code. This can be useful when you need to switch to another library, but can't afford to rewrite much of your code. In the following example we are modifying jQuery's $.when method to work with the WinJS.Promise. This is some code I wrote back when I worked for appendTo when we were making jQuery working with Windows 8 apps. You can find this repository at jquery-win8.

Much of the jquery-win8 repository is not needed anymore since Jonathan Sampson has worked with the jQuery team to make sure the changes he made to the shim was added to the 2.0 version of jQuery as noted in the following blog post


Observer


We've covered the Observer pattern already in the Blue Bird past a while back in this series, but it is a powerful pattern that can help decouple various components. My recommendation is to use the postal.js library.


Many More Patterns


Inheritance


There are several ways to implement inheritance in JavaScript. It is good to know some of these patterns as you create new objects in your application.

Prototypal Inheritance


Pseudoclassical Ineritance


Chaining


In the front-end world chaining became popular by the jQuery library. It is actually a really easy pattern to implement. You essentially just have to return this from every function so that other functions can be immediately called. See the following for an example.


Encapsulating


We've already covered encapsulating in the Red Bird past where we talked about the IIFE pattern. This allows you to have public and private properties and methods to help encapsulate your code. The follow is a very brief example of that. Check out the Red Bird post for more details.


Finite State Machine


One of my favorite pattern is the Finite State Machine. My friend Jim Cowart (@ifandelse) created the Machina.js Library to implement this pattern in JavaScript. The following is an example of using states to describe the game of Angry Birds. For more information check out his blog post and GitHub repository.


Recommendations


In addition to learning these patterns I would recommend that you pick one of your favorite libraries and start to source dive into their repository. There is a wealth of information you can learn there. At first it could be semi-overwhelming, but over time you can glean a lot from developers who really know some of these patterns. You might try just looking at one particular method and start picking it apart. If you aren't sure exactly where to look for a particular method why don't you pick jQuery and use James Padolsey's (@padosley) jQuery Source Viewer to help find it for you?

Additional Resources


There are far too many patterns for me to list here. Many have blogged about these before me and will continue to. If I have missed any good ones please let me know.


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 Big Brother Bird and you can also use the arrow keys.


Conclusion


The good news is you don't have to know all the answers to be successful in front-end web development, but what does help is knowing some of the common patterns that come up again and again during development. Once you get accustomed to these patterns it will become easier talking about these architectural solutions and figure out solutions should come quicker. Take some time and look through the recommended resources above and start mulling over some of them for yourself.

There is one more front-end architecture technique that has been stolen by the pigs. Tune in next time as the next Angry Bird takes its revenge! Dun, dun, daaaaaaa!

Tuesday, April 09, 2013

Angry Birds of JavaScript: Orange Bird - Templating

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


Orange Bird Attacks


In this post we will take a look at the Orange Bird. He first 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. Slowly, one by one, the birds will take back what it theirs to keep!

What Was Stolen by the Pigs?


For the last several years we have seen a trend that more and more work is being done on the front-end of web development. We communicate to the back-end via Ajax or Web Sockets and then display the data somehow in the UI. The birds found themselves mostly using string concatenation to build up the rich user interfaces, which resulted in a lot of code that was boring and also prone for errors. Thankfully an Orange Bird came along and said, "Hey, isn't there something better than this? Can't we separate our view from our data somehow?", and that is how templates became to be in the bird world. The Orange Bird borrowed templating libraries from the humans such as Underscore.js and Handlebar.js to help fit this need among the foul.

However, during a recent invasion the pigs stole the birds' templating libraries! As a result, one of the Orange Birds has been tasked to reclaim what has been stolen. He will use his exploding power to help destroy the pigs in order to take back what is theirs.

Why Use a Templating Engine?


Before we get into what templating engines I recommend let's first look into why we might need one in the first place. The more I develop I try to find ways to separate the various parts of my application. I start to feel dirty when too much stuff is going on in the same place. Take a look at the following piece of code and tell me how you feel...


Yeah, I don't like all of the string concatenation either. I prefer not to have a bunch of presentation inside of my code if I can help it. On the plus side, it does work. You can see the output of the code in the following embedded jsFiddle.



So, what can we do instead? This is where some type of templating engine can help us simplify our code and separate our markup from our code.

Underscore.js


We will first look at the template method in the Underscore.js library. I tend to use Underscore in all of my projects these days so I already have the power of its templating engine loaded. If what I am doing is pretty simple, then I mostly default to use Underscore for templating. However, as you'll see there are some limitations which make the next library we will look at much more appealing.

Take 1


The following is the above code rewritten using Underscore's template. You'll notice that the code piece has been greatly simplified! Whoo hooo!


The bulk of the work is being done by the template to explode it into a bunch of markup! As you can see to the left our orange bird looks quite different now lolz ;)

We moved the layout into a script tag in our markup and gave it an identifier. The template has special markers <%= expression %> to denote where it should evaluate data passed to it. You can also use the <% statements %> symbols to put whatever JavaScript you want in there (think loops, branching, etc...)!


You can play around with the above code snippets in jsFiddle.

As Uncle Ben said, "With great power, comes great responsibility."

Being able to put whatever code you want in your template isn't the best idea in the world. By putting the date manipulation logic in the template it makes it really tough to Unit Test that piece of code. Just imagine if we started cluttering our template with more and more code blocks that like. If you go this route, then you aren't really solving the original problem at hand which was combining presentation and logic.

Take 2


The following is another take at using Underscore, but this time doing the data manipulation before. The downside is that I'm using the _.map() method and converting each date property to the relative version. There is some overhead in me having to loop over the data before handing it off to the templating engine.


We were able to remove the date logic in the following template since we did that work above in the JavaScript before calling the template to do its work. The result is better than what we started with, but it could be better.


You can play around with the above code snippets in jsFiddle.

Why use Underscore.js?


Pros


  • You can stick arbitrary JavaScript in the template
  • It is very small
  • If you are already using Backbone.js then you have it
  • If you are already using Underscore.js then you have it
  • You can Compile the Templates
  • Can Run on the Client and the Server
  • Can you think of others?

Cons


  • You can stick arbitrary JavaScript in the template
  • Doesn't have the concept of this in templates
  • Can you think of others?

Handlebars.js


Overall I tend to prefer the Handlebar.js over Underscore's template engine. Handlebars encourages you to separate your presenting from your logic, it is faster, and it provides a mechanism to precompile your templates that we will look at here in a bit.

First let's take another look at the problem we have been addressing throughout this post. The following code uses Handlebars to template the solution. The code is still pretty clean as was the previous version. You'll notice that I am defining a custom helper called fromNow that can be used in the template.


And now for the templating syntax below. The syntax feels much more terse to me compared to Underscore, which I like. Inside the template we are using the fromNow template helper to convert the time. This is nice so we don't have to map over our array beforehand like we did with Underscore or put the logic in the template itself.


You can play around with the above code snippets in jsFiddle.

Precompiling Your Templates


I briefly mentioned above that one of the things I liked was that you can precompile your templates. What does that even mean!?! Well, with both Underscore and Handlebars you need to compile your template before you use it (technically you can do it in one step with Underscore, but it still has to be done under the covers). Compiling a template is good to do if you plan on using it more than once or if you just want it done before you need it.

However, with Handlebars you can go one step further and compile the template on the server and include that on the front-end. This means that you can reduce that amount of work needed on the front-end AND there is a trimmed down version of the handlebars runtime that you can use that has only the parts necessary needed to execute a template (not compile it)!

How cool is that? If your answer was "It's just about as cool as Batman riding on a Rainbow Unicorn alongside dolphins!", then you were right! Congratulations ;)

So how does that work exactly? Well, first you install Handlebars on your server using Node...


Then you take your template contents (what is between the script tags) and save it to a file. In our case let's save it as tweets.tmpl. How run the handlebars precompiler against your template file.


Once all of that is done you have a precompiled version of your template that you can now include on your front-end application like the following...


Now that your template is available on the page you can access it by asking Handlebars for the precompiled version and you are all set to start using it!


Why use Handlebars.js?


Pros


  • Its a Logic-less Template Engine
  • You can Precompile Templates on the Server
  • Supports Helper methods
  • Can Run on the Client and the Server
  • Supports the concept of this in templates
  • It iss a superset of Mustache.js
  • Can you think of others?

Cons


  • Can you think of any?

What About Other Templating Engines?


That is a great question. Maybe your needs are different than mine or maybe you just don't like one of the engines that I've mentioned. If that is the case then you should check out a great tool created by Garann Means (@garannm) called the Template Chooser. The chooser will ask you a set of questions that will help determine which templating engine is right for your needs. The following is an example of what the chooser looks like...


Additional Resources



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 Orange Bird and you can also use the arrow keys.


Conclusion


Mixing markup in code can lead to some nasty looking code that is cumbersome, monotonous, and difficult to maintain. Being able to split these apart is a great benefit for developers to simplify their code and help keep each concern in its place. Thankfully libraries like Underscore and Handlebars help us out by providing a clean way to describe presentation apart from logic. THere is a lot of freedom depending on what library you use, but I'd encourage you to look around and find one that works for you. The answer to that may be not to use one and that is fine.

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!