Friday, April 12, 2013

AngleBrackets Sessions and Slides

I had a great time this week at the AngleBrackets conference in Las Vegas, NV. It was the first year for this web focused conference.

I was honored to speak alongside John Papa (@john_papa), Dan Wahlin (@danwahlin), Scott Hanselman (@shanselman), Christian Heilmann (@codepo8), Lea Verou (@LeaVerou), Denise Jacobs (@denisejacobs), Jim Cowart (@ifandelse), Todd Anglin (@toddanglin), Burke Holland (@burkeholland), and more....

Thanks you for everyone who was able to attend my talks. It was great to meet you all. I enjoyed our conversations and your questions. I hope to see you all around at another conference in the near future! The following are the talks that I gave this past week.

Angry Birds of JavaScript


AngleBrackets was the first time I've given my Angry Birds of JavaScript talk based on the blog series that ended yesterday. You can click the following image to see the slides.

I used the reveal.js slide presentation framework for my slides. You'll need to down-arrow down to drill into each topic and then right-arrow to the next topic. The last slide of the Red Angry Bird is an interactive game. You have to destroy both pigs before you can proceed to the next topic ;)


Introduction to Backbone.js


I've given this talk once before, but I tweaked the slides somewhat since then.



Other Sessions


You can view the slides from the other sessions at the AngleBrackets website.

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!

Monday, April 08, 2013

Angry Birds of JavaScript: Green Bird - Mocking

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


Green Bird Attacks


In this post we will take a look at the Green Bird that can penetrate all of those hard to reach places and will mock and spy those stealing swine right where it hurts!. Slowly, one by one, the birds will take back what it theirs to keep!

What Was Stolen by the Pigs?


For the most part the birds are all front-end web developers only and don't focus on the back-end much at all. As a result the birds have a symbiotic relationship with the Water Buffalo. The Buffalo write the back-end of the application and the birds develop the front-end. The problem with this arrangement is that while the back-end is being developed the birds are left twiddling their feathers until the Buffalo are finished. However, once the back-end is done the pressure is on the birds to deliver while the Buffalo sit idle by the watering hole in the shade. Thankfully, a while back, a Green Bird proposed the idea of mocking the back-end services so they could make progress on the front-end while they waited for the Buffalo to finish their work! The Green Bird introduced a couple of handy libraries to make mocking a much easier process.

However, during a recent invasion the pigs stole the birds' mocking libraries! As a result, one of the Green 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.

The Twitter Application


We are going to take a look at a simple Twitter application that gets the tweets from a specific username. Why Twitter? Well, the Angry Birds have a special relationship with Twitter, especially the Blue Bird ;)

The following application grabs data from Twitter using JSONP. I thought about using Backbone.js to write the little application, but thought that might be overkill to introduce the mocking concept. You will also notice I am not using a templating engine and that is on purpose. Another Angry Bird will be introducing that concept ;)


The above code snippet is running in the below embedded jsFiddle. Feel free to run the code and launch the editor to play around with it.

Twitter Application using api.twitter.com




The data that comes back from Twitter looks something like the following screenshot...


Mocking Static Data


What if Twitter goes down, is unstable, or you just want to test your application without having internet access? This is where being able to mock the back-end service can be really helpful. Thankfully we can use a jQuery library called Mockjax. All you need to do is call $.mockjax and provide a URL that you want to listen for and a response that you want to be returned. The following is an example of mocking the call to api.twitter.com and passing back some static data.


Not only is this pretty cool and can be helpful for developing the front-end independent from the back-end, but it also very handy when writing Unit Tests that use Ajax.

The above code snippet is running in the below embedded jsFiddle. Feel free to run the code and launch the editor to play around with it.

Twitter Application using Mockjax




The data that comes back from Mockjax looks something like the following screenshot...


Mocking Dynamic Semi-Random Data


One of the downsides of this technique is that generally I am pretty unimaginative and lazy when making static data examples. I typically end up have the same object and just increment some of the values by 1 or something. That is fine and all, but it is a nuisance, it takes time, and it doesn't really give you an idea of what the UI could look like. Thankfully there is another nice library for that called mockJSON. You provide a template of what you want your data to look like and then you give it some metadata about what types of fields you want, how many, etc... The following is how I rewrote the previous example, but will randomly generate anywhere from 5 to 10 twitter objects to be displayed.



The above code snippet is running in the below embedded jsFiddle. Feel free to run the code and launch the editor to play around with it.

Twitter Application using Mockjax & mockJSON




The data that comes back from Mockjax with mockJSON looks something like the following screenshot...


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


Conclusion


It can be difficult to develop both the front-end and back-end independently. Thankfully there are some techniques and libraries today that can enable the front-end to develop and prototype separate from the back-end progress. The mocking techniqiue with static data can also be helpful when Unit Testing your code as well.

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!

Thursday, April 04, 2013

Angry Birds of JavaScript: White Bird - Linting

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


White Bird Attacks


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

What Was Stolen by the Pigs?


The birds all learned how to program in a slightly different way. Some birds were self-taught and some birds went to college for computer science. Even among those groups there were a wide range of experiences and talent. When the birds got together to build their first large application it was a huge disaster. Each bird thought their coding standard was the "right way" and it started to become an issue. One day a wise White Bird came along and suggested that they come up with a common set of coding practices to follow. In addition, the White Bird introduced a few tools to help them conform to a standard and to help find issues and concerns early before they became a huge issue later.

However, during a recent invasion the pigs stole the birds' coding standards document and their code quality tools! As a result, one of the White Birds has been tasked to reclaim what has been stolen. He will use his overwhelming power of quality to help destroy the pigs in order to take back what is theirs.

JavaScript Coding Standards


There are many coding standards out there to choose from. The most important thing is that you pick one and stick to it. If you are working with a team, they should also agree on some standard. If you can't find a standard you exactly agree on, then find one that is close and make some exceptions.

By doing so you'll find that...

  • A developer will be able to make sense of other code more quickly
  • Merges in your code repository won't be as awful
  • Having a standard will actually reduce defects
  • The codebase will feel more unified
  • Disagreements about who is "right" will lessen
  • ... insert your benefit here ...

Here are some of the coding standards that I am aware of...


Addy Osmani (@addyosmani) has a nice post entitled JavaScript Style Guides And Beautifiers that covers some of these styles in depth with examples showing how to abide by the standards recommended.

JavaScript Linting


A linter is a tool that helps find errors and possible issues with your code. In many cases it can help enforce whatever coding standard you chose from the above list.

There are actually several JavaScript linters out there, but the one I like the best is JSHint created by Anton Kovalyov (@valueof). It grew out of a community effort to fork the popular JSLint library written by Douglas Crockford. I've enjoyed watching the project grow and see bugs and new features being added. JSHint has a lot of options that you can choose to opt-in or opt-out of which enables a team to figure out what works best for them.

Some of the standard checks that JSHint can verify include...

  • The use of === instead of ==
  • Using variables that aren't defined
  • Declaring variables that are never used
  • Declaring functions inside of loops
  • And lots more...

For a full list of options see the JSHint Docs.

Some of the more recent additions that I've really enjoyed include:

  • maxcomplexity - Maximum cyclomatic complexity (see following Wikipedia quote)
  • maxstatements - Maximum number of statements allowed in a function
  • maxparams - Maximum number of parameter allowed in a function
  • maxdepth - Maximum depth allowed in a function
  • maxlen - Maximum length of line in code

"The cyclomatic complexity of a section of source code is the count of the number of linearly independent paths through the source code." --http://en.wikipedia.org/wiki/Cyclomatic_complexity


The following errors are generated by JSHint after running it against the above code snippet.


Thankfully you don't have to run JSHint from the website every time to check your code. There are several ways to integrate it into your code editor of choice:


In the Mighty Eagle post we'll talk about another way to use the JSHint from the command line and automatically.

JavaScript Analysis


Code linting is great, but sometimes it is nice to get a high level overview of your codebase and then be able to drill down and analyze small portions of your application.

Thankfully there is a tool called Plato that will analyse your code and provide a visual report where you can view the complexity of your application. The tool runs in Node and you can install it using npm install plato -g.

Once installed you can run the tool on the command line by plato -r -d report myDirectory, which will recursively analyse the code in the myDirectory folder and export the results to the report folder.

If you were to run the report on the jQuery source code it would look much like the following report. As you can see, the average number of lines is decreasing over time, which is good. The maintainability is decent and then a breakdown of the maintainability of each JavaScript file is listed in a bar chart. Further down in the report there are a bar charts for Lines of code broken per file, Estimated errors per file, and also JSLint errors per file.


If you drill into one of the particular files from above you'll see a view that looks like the following. The nice part about this report is that it breaks down each function into complexity and lines of code in a way that is easy to grasp. You can quickly jump to various parts of the file to review the concerns the tool is identifying.


You can view the above jQuery Report from Plato's GitHub repository.

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


Conclusion


Front-end web applications can get complicated quickly. If your developers aren't all on the same page then things can fall apart in a heartbeat, especially on a large project. Having a unified coding standard and implementing some tools to help find issues before they become a problem can really help to make your project a success.

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!

Wednesday, April 03, 2013

Angry Birds of JavaScript: Black Bird - Backbone

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


Black Bird Attacks


In this post we will take a look at the Black Bird who will use the organized approach of the Backbone.js bomb to fight these porkers. Slowly, one by one, the birds will take back what it theirs to keep!

What Was Stolen by the Pigs?


The birds used to write their jQuery code like it was a tangled smorgasbord of worms. They would mix up their views, models, and presenter logic all together in a big interconnected pile of grubs. After a while one of their ancestors, a Black Bird, introduced the Backbone.js library and showed them a different way to think about developing front-end web applications. However, during a recent invasion the pigs stole Backbone.js from the birds and carried it back to their filthy sty.

One of the black birds has been tasked to reclaim what has been stolen. He will use his explosive power of organization to help destroy the pigs in order to take back what is theirs.

Tangled Smorgasbord of Worms


Let's take a look again at the following application that the Blue Bird dealt with in a previous attack. Instead of adding messages to untangle the mess we are going to introduce how using Backbone.js can help us out. Here is the running application below...

It appears Plunker is not embedding correctly at the moment. The application is a simple Netflix search interface that will show the results from Netflix. If Plunker doesn't start working soon I will move the demo somewhere else. Sorry for the inconvenience.



And to refresh your memory, here is the supporting code used for the above web application. You should notice that a lot of concerns are all being mixed together (DOM events, Modifying the View, AJAX Communication, etc...)


Do you see the problem? It is so tempting to write code like the above, but I hope you see that it can be a bear to work with and maintain. Don't worry, we have all written code just like the above. The good news is that we don't have to continue to write it that way. Let's take a look at what Backbone.js is and how it can help us out in this situation.

There are many other MV* front-end frameworks (Knockout, or AngularJS, EmberJS, & others) that could also bring structure to the above code. I would encourage you to pick a tool that you can be productive with and get comfortable with it.

Backbone.js Basics


Backbone.js has several pieces that can all work together to make a web application. You don't have to use all of these components, but they are available if you choose to use them.

  • Model - Represents data and logic surrounding it
  • Collection - Ordered sets of Models
  • View - A module backed by a Model with a render method
  • Router - Mechanism to provide linkable, sharable URLs
  • Event - Observer Eventing module
  • History - Provides the ability to maintain history (back button support)
  • Sync - Extendable component providing RESTful communication to the server

Refactoring the Tightly Coupled Code


Let's take a stab at refactoring the above jQuery mess and use Backbone.js to split out some of the various concerns.

I'm not going to dive into all of the above pieces in this post, but will focus on 3 of the main pieces (Models, Collections, and Views). I'll touch on some of the Sync concerns, but as part of the other topics. I'll have resources listed at the end if you want to dig deeper into any of these topics.

RequireJS


Before we get into the Models, Collections, and Views I want to show you how we took out all the scripts from the index.html page and used RequireJS to help us out.

If you've never seen RequireJS before then you might want to check out the previous Yellow Angry Bird Post about RequireJS.

main.js


The above code is defining the paths for jQuery, Underscore, Backbone, Postal, and Bootstrap. We needed to shim Underscore, Backbone, and Bootstrap since they are not defined as AMD modules.

Then the require function is called to request a set of dependencies before the callback is invoked. At that point, jQuery and all the other views and models will be ready for usage!

Models


We are going to make 2 models (Search and Movie) to represent the above application.

The following Search Model is really simple and its main job is to respond when the term property has changed. We are using Backbone's events (Observer Events) to listen to changes on the model and then propagating the message to Postal.js (Mediated Events). For more information about those terms and how they are different you can reference the Blue Angry Bird Post about events.

search.js


The following Movie Model doesn't have a lot going on as well. It's main purpose is to parse the data returned from the server and map the results to something a little more manageable. In this case we are only concerned with the releaseYear, rating, and name properties.

movie.js


Collections


As we described above, collections are just a set of models. The following code is just a set of Movie models. The collection is where you define where to get the list of models from the server. The back-end for this application is Netflix and their endpoint is a little complex so we are using a function to dynamically build that URL. We also defined a parse method to get directly to the array of contents that will be mapped to Movie models. Since this AJAX call will be using JSONP we also needed to override the sync method and provide some additional options.

movies.js


Views


I see the View as more of a Presenter than the typical MVC View you might normally think of. Anyway, We have 2 views in this application that we will briefly look at.

The following SearchView handles the interactions with the DOM and the Model. The events property primarily is used to listen to DOM events and in this case is watching for clicks on the button or previous search links. Changes to these elements will be stored in the model as term. The initialize method sets up some events listening for changes in the term property. If term changes, then portions of the UI will change accordingly.

search-view.js


The MovieView below is a little different than the above view. The first thing to point out is the weird text!movie-template.html. I am using the text.js plugin for RequireJS that let's us pull text resources as part of the dependency chain. This is really helpful for markup files used when using a templating engine or possibly a CSS file that is associated with a particular widget. Inside of the initialize method we are subscribing to a change in the term and then asking the collection to fetch the information from the server. The render method gets called after the data is retrieved from the server and we use Underscore to template the results to the DOM.

movie-view.js


The following is the template file in case you were wondering. I'm using Underscore's templating engine which is similar to John Resig's micro-templating implementation that he wrote years ago. There are other templating libraries available, but I used this one because it comes with Underscore which is a prerequisite for Backbone. If I needed something more featured I would have used Handlebars instead, but that is a story for another Angry Bird ;)

movie-template.html


Additional Resources


I only scratched the surface on all the things you can do with Backbone.js. If you are interesting in learning more about these concepts you may want to look at some of the following resources.

The following resources were taken from the Beginner HTML5, JavaScript, jQuery, Backbone, and CSS3 Resources blog post.


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


Conclusion


Front-end web applications can get complicated quickly. Before you know it you have a pile of interconnected mess if you are not careful. Thankfully Backbone.js provides components to help you split out your application into consumable pieces that each have their own purpose. Thank you Black Bird for returning Backbone back to the birds. They will be able to rest easier knowing things are organized and in their proper place.

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!