Wednesday, November 13, 2013

New Pluralsight Course: jQuery-free JavaScript


My latest course, jQuery-free JavaScript, has recently been published on Pluralsight. Thus far I've had a mix of both JavaScript and jQuery courses on Pluralsight, but this time I thought I'd focus on when you may consider not using jQuery and what that might look like.

In this course I explain when it's appropriate to use jQuery and when it may not be. If you do need jQuery then I'll discuss making a custom build that includes only the parts you need. The rest of the course is focused on converting common jQuery snippets to either use native browser APIs or utilize a popular micro-library.

Don't get me wrong, I love jQuery. It has proven its value and it very much has its place. However, you may have seen some buzz around the web about the concept of not using it at all.

If you are looking to write a Single Page Application (SPA), then I wouldn't recommend going this route. In that case I'd go with AngularJS, Backbone.js, Ember, or something along those lines. However, if your website or application is pretty basic and you are looking for fast interactions with a small footprint, then jQuery-free JavaScript may be something that you should consider.

In addition, it is just a good idea to know how to get around the native DOM without the necessity of a helper library such as jQuery, Dojo, MooTools, Prototype, etc...


Tuesday, October 22, 2013

Front-End Web Dev Jokes

You may have noticed recently that I've tweeted some Front-End Web Developer jokes here and there. The feedback I've received has ranged from "Ha ha" to "Groan" to "Unfollow". I think most of those responses are out of fun, but who knows :) Others have encouraged me to continue making more jokes and have wondered where they can see a list of all the puns.

So, without further ado here are the jokes I've authored thus far. Please, don't groan all at once...

q. How do you comfort a JavaScript bug? a. You console it
When a JavaScript date has gone bad, "Don't call me, I'll callback you. I promise!"
Dev1 saw a strange JavaScript function & asked, "What is this?". Dev2 responded, "I don't know. I would've called you, but I was in a bind"
Two JavaScript developers walked into the variable bar. Ouch!
q. Why was the JavaScript developer sad? a. Because he didn't Node how to Express himself
q. Why did Jason cover himself with bubble wrap? a. Because he wanted to make a cross-domain JSONP request
q. Why did the software company hire drama majors from Starbucks? a. Because they needed JavaScript experts!
q. Why did the CoffeeScript developer keep getting lost? a. Because he couldn't find his source without a map
q. What do you call __proto__? a. Dunder proto q. Michael Scott was the regional manager where? a. __mifflin__
q. How did the doctor revive the developer? a. The dev wasn't responsive so the doc picked him up by his bootstraps
q. Why did the developer go broke? a. Because he used up all his cache
q. Why did the C# developer fall asleep? a. Because he didn't like Java.
q. Why did the JavaScript boxer goto the chiropractor? a. Because his backbone was angular from a knockout and required attention
q. How did the web developer hurt Comic Sans feelings? a. Once he saw the font he quickly changed it to Open Sans and exclaimed "In your @font-face!"
q. Why do C# and Java developers keep breaking their keyboards a. Because they use a strongly typed language
q. Why was Ember.js turning red? a. Because it was EMBERrassed for not remEMBERing its route home
q. Why did the jQuery developer never have financial problems? a. Because he was in $.noConflict() mode

Yeah, I know those were very cheesy pun-like jokes, but that is how I roll ;) I hope you somewhat enjoyed the jokes... if not, that's no problem too. I hope you have a great week and enjoy yourself today.

Monday, September 30, 2013

Develop with Purpose

So, you might have seen the following tweet from me a few days ago...


Well, today is the day! I started a new full-time job with...

The Lampo Group! If that doesn't ring a bell, then think Dave Ramsey's company ;)


During the past year there has been a lot of transition for me. I worked with the great talent at appendTo, then decided to start my own business and made several training videos with Pluralsight.

I've known about Dave Ramsey for several years. We have been through his Financial Peace University course years ago and it is what prompted us to pay off our vehicles, credit card debts, and completely get out of debt excluding our house.

Someone I went to college with works for Dave and has been there 6 or 7 years, which is very rare in our field. Over time I've met more and more people that also work there and love it.

Historically the developers at Dave Ramsey have been generalists working both on the front-end and back-end, but recently I saw a tweet from @devwithpurpose saying that they were looking for a Front-End Web Developer specialist... and HEY, that describes me!

So, I applied and over a several month interview process they offered me the position. I am very excited for many reasons...

  • Getting back to a regular consistent work schedule
  • Getting to work on Front-End Web Development
  • Getting to work on something that has a bigger purpose and is based on Biblical principles
  • Getting to work somewhere where there is a history of longevity
  • Getting to work alongside some very talented developers and designers

Thursday, August 22, 2013

New Pluralsight Course: Fixing Common JavaScript Bugs


I'm pleased to announced that my last Pluralsight course has been released Fixing Common JavaScript Bugs.

This is not your typically "Let's learn JavavScript Course" from beginning to end. You can think of this course more like various episodes of Sherlock wherein you unexpectedly encounter a piece of dead rotting JavaScript and you must use your keen detective skills to identify and unpack the reason for its demise. And then, armed with the knowledge of the crime, you will be able to reconstruct the code back to it's original glory.

Since each clip is a mini-mystery, the names of the clip is more of a clue in order to not give away the culprit. However, to give you a taste of what you will encounter, here are some of the topics within...
  • Rules for Automatic Semicolon Insertion
  • Rules for how values are coerced when using ==
  • Different techniques to control the `this` implicit parameter
  • What hoisting is and how it can be different when declaring functions
  • Benefits of strict mode and a gotcha to watch out for
  • Gotchas with trailing commas
  • Reserved words and what to watch out for
  • Strange things when using numbers
  • Issues you may run into when checking types
  • The importance of truthy/falsey
  • Fake function overloading
  • When to use a closure and what one looks like
  • Various ways converting from one type to another
  • Weirdness with type wrappers
  • ... and more ...

Regardless if you use VanillaJS, jQuery, Backbone.js, AngularJS, KnockoutJS, Ember.js, or any other various library or framework, you will inevitably run into a JavaScript bug and will need to debug it. The focus of this course is not "how to debug", but rather the goal is to equip you with the knowledge of "how to identify a bug". In addition, we'll unpack what really is going on so that hopefully you can protect yourself from making future bugs or at least fix them quicker.

Do you feel like a little code mystery? Fire up your screen of choice (iPad, Apple TV, laptop, etc) and take a stab at Fixing Common JavaScript Bugs.

Thursday, August 15, 2013

Front-End Web Dev Trading Cards


NOTE: These trading cards don't actually exist. They are only a thought exercise :)

We should have front-end web development trading cards! I bet this would go wild on Kickstarter... or not, I don't know. I didn't grow up in a sporting family. Baseball trading cards seemed like a neat idea to me, but I wasn't interested in the subject.

I was talking to a group of individuals the other day and they didn't recognize one of the above front-end web developers. These were intelligent and forward thinking developers so it was an "Ah ha" moment for me. At one point I didn't know the above developers either, but I now see them as some of the most influential individuals in my field. It is often times difficult to know what resources we should be reading, where we should be learning, who should we be watching, and where are the places we can join in the effort.

At one point or another we all didn't know who the above developers were, but maybe having trading cards could help bring certain influencers to our attention. Why is that important? Because of their impact they have shaped the way our industry works. You may not agree with all of their ideas or frame of mind, but it is important to know where they are coming from and what they are trying to accomplish.

I could have made many more cards and I actually found it difficult to only pick a few. Who would you have on your trading card and why?

So What Is There Then!?!


So, if we don't have actual front-end web developer trading cards, then how does someone know who and where to look?

Currently the nicest resource that I know that specializes in helping a developer know who and where to look for what is going on in Front-End Web Development is http://uptodate.frontendrescue.org/

The website lists people to follow on twitter, blog to watch, newsletters to read, podcasts to listen to, and conferences to attend.

In addition you can also follow their @frontendrescue twitter account.

Wednesday, August 14, 2013

Reducing Filter and Map Down to Reduce

You've probably seen some of the new array methods in ECMAScript 5 (ES5) and you may have even used some of them before, but have you used the .reduce() method?

Not So Common Use Case


If you were anything like me, I first went and looked for some examples of how to use the .reduce() method. Most of the examples that I ran across all looked the same and didn't really seem very convincing to me. Most of the examples I found were adding up numbers across various objects. Here is the type of code that I saw...


Adding up values across a collection does seem like it could be helpful on occasion, but it didn't seem like it would be a very common use case in my day-to-day development. Deep down somewhere in my inner-algorithm I felt like there must be a better use case for this lowly .reduce() method. I wanted so much more for it.

SPOILERS: There is a better use case ;)

Data to Manipulate


So, before we proceed let's take a step back before revisiting the .reduce() method again. Partly to celebrate the announcement of the 12th Doctor and to make things a little more interesting we are going to use data about the 12 Doctors as we unpack .filter(), .map(), and .reduce(). Here is the data we will be using throughout the rest of this blog post.


Problem to Solve


What we want to do is to take all the Doctors from year 2000 until today and change their data up just a little bit. We want to massage the data a little bit and have keys of doctorNumber, playedBy, and yearsPlayed. We don't want to just directly map one field to another, but for doctorNumber we want to prepend a "#" and for the yearsPlayed we want to want how many years the doctor played and not a range.

Desired Output


Based on the above problem that we want to solve, the end result of our data manipulation should produce the following results.


So, let's first use the .filter() and .map() methods to solve this, and then we will redirect to solve the same problem using the reduce method.

Filter and Map



ECMAScript 5 Array Filter and Map


IE9+ and other modern browsers implement ECMAScript 5 and with that comes a lot of nice features in JavaScript. Some of these nice features are additional array methods. Two of these handy methods are .filter() and .map().

Here we use the .filter() method to narrow down the array items to only those that include Doctors that only began past the year 2000. The method will iterate over your array of items and invoke the function you provided passing it as an argument. If you return a truthy value from the function then that means you want to keep the item in the resultant array otherwise the item will not be included in the result.

The result of the .filter() method is an array so we then immediately call the .map() method off of that array. This method also iterates over the array, much like the .filter() method did, but the return inside of the function argument for .map() defines what that object will look like in the new array. In this case we are changing up our object to use new keys and to change up the values slightly.


ECMAScript 5 Polyfill


If you are using an older browser (IE8 or less) then you won't have the ES5 methods available to you. However, you can still use the above code if you provide a ES5 polyfill to fill in the functionality gap. A polyfill is a library that will mimic a native browser's API if it isn't available. HTML5Please recommends either using es5-shim or augment.js if you want to support ES5 methods.

The nice thing about a polyfill is that if the native feature does exist, then it will be used. The polyfill should only kick in if the browser does not provide the functionality you are expecting. The idea is that your code can be written in such a way that it follows the official browser API and hopefully one day you won't need the polyfill anymore or at least not many people will need it.

Underscore Filter and Map


Instead of using the native ES5 array methods or using a polyfill, you could instead decide to use a library such as Underscore or Lo-Dash. These libraries contain many helper utilities methods that I find helpful in most every web application I write. Two of many methods provided are .filter() and .map().


The code is very similar to what we had before. The main difference is that we need to split out our two method calls. This is a little cumbersome, but it makes sense because the methods return an array and we can't chain them together and continue to call Underscore methods.

Underscore Chaining


Thankfully, there is a way in Underscore that we can chain these together if we want to. There is some extra syntax sugar that we need to sprinkle, but it isn't too much.

The main thing you have to do is the call the .chain() method and pass in the array that you want to use while you chain Underscore methods. From then on you just keep calling Underscore methods as you like and it will share the array among the various methods. At the point you are ready to get the result of your manipulations you can call the .value() method to get the value.


I personally don't use Underscore's chaining mechanism, but it is nice to know that it does support that feature.

Reducing Filter and Map with Reduce


So, back to the main topic of this blog post. After finding the same use case over and over again on the internet (summing up a property over a collection) I then approached some friends of mine to see if they knew of another use case for the .reduce() method. The infamous Jim Cowart came to the rescue! He actually had written a blog post about this very topic called Underscore – _.reduce().

ECMAScript 5 Reduce


So, let's convert the above .filter() and .map() code above and convert it to use the .reduce() method instead. As the first argument you provide the .reduce() method a function that will be invoked for each item in he array. In addition this method also takes a second memo argument that will be passed from one iteration to the next. Instead of passing a number, like we did at the beginning of this post, we are going to pass an empty array. Then inside our function argument we will have an if statement, which will serve as our "filter", and if our criteria is matched we will push a new value to our memo array. The "map" happens as we push a custom object onto our array. Before we finish our function we need to return the memo array. Once the statement has completed then a new array will be returned that will be the filtered and mapped version that you wanted.

NOTE: The above polyfills listed also include the .reduce() method.


Underscore Reduce


Much like our previous examples, you can also use the .reduce() method from Underscore or Lo-Dash instead of the native or polyfilled version.


Other Methods


If you like what you see with .filter(), .map(), and .reduce() then you are in luck because there are many more methods that you can use that are available both in ES5 and also in Underscore or Lo-Dash. Knowing what is available is half the battle ;)

Wednesday, July 24, 2013

New Pluralsight Course: jQuery Tips & Tricks


I'm happy to announce that I have another new course on Pluralsight called jQuery Tips and Tricks that I co-authored with Dan Wahlin. It was an honor to work alongside Dan and to get to know him better in the process.

"jQuery provides a powerful set of features that can be used to build applications but do you know some of the key tips, tricks and best practices that can be used to reduce code, promote re-use and simplify maintenance? In the jQuery Tips and Tricks course Dan Wahlin and Elijah Manor will walk you through key tips and tricks learned over the years of building applications with jQuery. Topics covered include tips and tricks related to working with the DOM, handling and triggering events, making Ajax calls, working with and caching data locally, as well as taking advantage of built-in jQuery utility functions."

You might be wondering how the above course is different from another course I recently published called Fixing Common jQuery Bugs. The new course focuses on showing best practices when using jQuery and revealing some of the hidden and underlying concepts. Whereas, my previous course teaches from another viewpoint. The fixing bugs course tries to focus on issues that you might run into and then uncover what is going on and how to fix the problem. There is a little overlap, but the majority of the content is different between the two courses.

I hope you enjoy the courses and thanks for those that have watched or are going to watch!

Monday, July 01, 2013

New Pluralsight Course: Fixing Common jQuery Bugs


I'm pleased to announce that my 2nd Pluralsight course Fixing Common jQuery Bugs as been released!

In the course I examine common bugs that are often accidentally introduced when developing with jQuery. For each bug I expose the problem, explain what is going on, and then exterminate the issue with a solution. The goal is to help prevent you from making these mistakes and in the process gain a better understanding of how jQuery works.

The course is loosely based off a blog series and talk that I gave over a year ago that you might remember. I took some of those older topics, added a bunch of new content, and then bundled them into this new course. I also tried to insert some of my strange quirky sense of humor. It should be interesting to see how that goes over ;)

The bugs examined in this course range from core calamities, selector stew, traversing travesties, manipulation mix-up, erratic events, Ajax agony, embarrassing effects, unsettling utilities, and perplexing plugin related issues.

Since each bug is essentially a mini quiz, the names of each title ended up being slightly obscure. However, hopefully after I've exposed the actual issue the name will make a little more sense.


Tuesday, June 04, 2013

Unit Test like a Secret Agent with Sinon.js

The following content comes from the forth module of my Pluralsight course entitled: Front-End First: Testing and Prototyping JavaScript Apps. The rest of the course covers an introduction to Unit Testing, Examples of Hard to Test Code, Mocha (a JavaScript test runner), Grunt (a JavaScript task runner), Mockjax (a way to mock Ajax requests), mockJSON (a way to generate semi-random complex objects for prototyping), and more.

Introduction


“Standalone test spies, stubs and mocks for JavaScript. No dependencies, works with any unit testing framework.”

Sinon.js is a really helpful library when you want to unit test your code. It supports spies, stubs, and mocks. The library has cross browser support and also can run on the server using Node.js.

Spies


“A test spy is a function that records arguments, return value, the value of this and exception thrown (if any) for all its calls. A test spy can be an anonymous function or it can wrap an existing function.”

Example


A test spy records how it is used. It will record how many times it was called, what parameters were used, when it was called, and a bunch of other things. Here you can see an example of creating a spy and I've listed out only a small subset of it’s features such as called, callCount, calledWith, threw, returned, and more.


In addition to just creating a new spy, you can also take an existing function and turn it into a spy. In this example we are taking jQuery and turning it’s ajax method into a spy. Once the spy has been used you can actually pull out one of those instances and verify how that particular call was used. And again, it is important to restore the function back to it’s original state much like we did when we manually stubbed our functions previously.


Mission Impossible: Spy


In the following simple code example we are creating a new ethanHunt spy and passing it to the missionImpossible.start method.

As you can see the start method takes the agent that was passed in and immediately invokes it.

The spy will record how it is used and then you can observe what happened.


At this point we can interrogate ethanHunt if he was called or not, how many times it was called, and a bunch of other questions.


Stubs


“Test stubs are functions (spies) with pre-programmed behavior. They support the full test spy API in addition to methods which can be used to alter the stub's behavior.”

A stub in Sinon.js is also a spy as we've just seen, but it is also a function that has some predefined behavior. A stub is used when we want to fake some functionality so that our system thinks everything is performing normally.

Example


You'll see here that after we have created a stub we can optionally respond to it based on the parameters that are passed to it.


Here we are telling our stub that if "Hello" is passed to it that it should return the string "World" and if we pass "Wuz" to the stub that "Zup?" should be returned.

We can do other things like if "Kapow" is passed to our stub then an exception will be thrown and we can get even more sophisticated and say if an object is passed to the stub it should yieldTo (or invoke) the call function that was passing using the "Howdy" argument. This is some pretty serious and awesome functionality built into these stubs!

Mission Impossible: Stub


In this next mission, if you choose to accept it... we are stubbing out a tape function that will be passed into an assignment method.

The tape will either be passed the string "accept" or "reject" and depending on the answer we want a different result.

With a sinon stub, that is no problem. We can just say tape.withArgs("accept"). returns(new Mission()) and if we wanted to throw a Disintegrate exception if the tape was rejected then we just follow the same pattern... tape.withArgs("reject"). throws("Disintegrate").

If you can't tell already these stubs are really powerful and a great addition to your testing toolkit.


Once we've set up our stub, we can exercise our code as we would normally and the stub will respond with whatever behavior we predefined. Below you'll see that once we pass "accept" that we are getting a Mission object back and if we "reject" the assignment that a Disintegrate exception is thrown.


Stubbed Unit Test


Let’s take an example Twitter unit test and show how we can use a stub to simulate a response from jQuery’s ajax method.


In the before hook we will ask Sinon.js to create us a new stub based off of jQuery’s ajax method and we want to yieldTo (or invoke) the success function from the object that is passed to it. And while we are at it we want to pass our fake twitter data along with the success function.

With that one line of code we have stubbed out the jQuery ajax method and provide fake test data that we can use in our unit test.

Again, it is important to clean up after ourselves so in the after hook at the bottom here we are taking the jQuery.ajax method and calling restore which removes all of the stub behavior from the function,

Mocks


“Mocks (and mock expectations) are fake methods (like spies) with pre-programmed behavior (like stubs) as well as pre-programmed expectations. A mock will fail your test if it is not used as expected.”

Now we finally get to mocks. Mocks are a lot like a stub and a spy, but with a slight twist. With a mock you define up front all of the things you want to expect ( or happen ) then when you are all done with your tests you assert that all those things happened as planned. So, it’s a slightly different way to think than if using a spy or stub by themselves.

Example


In the following code we are defining a mock based off our opts object and we are saying that we expect the call method should only be called once and when it is called that it should have the "Hello World" string argument passed to it.


Then we proceed to run our code that we want tested. You'll see here I’m calling the call method passing the "Hello World" string.

And then at the end you tell the mock object to mock.verify() that all of the expectations you've made previously are valid. If for some reason an expectation was not met, then an exception will occur. And then just like in most of the other examples, we need to clean up after ourselves and call the restore method off of what was mocked.

Mocked Unit Test


Let’s take another look at the Twitter getTweets unit tests again, but this time use a mock instead of a stub.


In the before hook I’m creating a mock of the jQuery object and I’m expecting that the ajax method will only be called one and that it should invoke the success method of the object I pass in with some fakeData I've provided.

Inside my unit test I run the code I want to tests, which is the getTweets method, and then on the callback I call the verify method off of the mock to make sure my expectations have been met.

And as before I restore the object in the after hook.

Fake Timers


“Fake timers is a synchronous implementation of setTimeout and friends that Sinon.JS can overwrite the global functions with to allow you to more easily test code using them.“

Another handy feature of Sinon.s is that you can fake timers! At first this might seem strange, but it turns out it is really powerful and clever.

Example


We first start by asking Sinon.js to useFakeTimers() and save off the clock it gives us. Now let’s take some jQuery animation code that will fadeIn an element slowly onto the screen.


Normally if we wanted to test if this element showed up on the screen we'd either need to provide a callback when the animation is finished or tap into the promise created from the deferred and wait for that to resolve.

However, much like a time lord we can take sinon’s TARDIS, errr... I mean fake timer and tell the clock that we are now 650 milliseconds in the future! And then we can immediately assert that the element is visible without waiting. And of course we will need to restore the clock back to normal when we are done.

Fake Server


“High-level API to manipulate FakeXMLHttpRequest instances.”

Another neat feature that Sinon.js has is a fake server. This is a high level abstraction over the FakeXMLHttpRequest that Sinon.js also provides if you need more granular support.

Example


We can create a fake server from Sinon.js, and we can define that for a GET to the /twitter/api/user.json resource we want to respond with a status code of 200 and the following JSON data.


Then if we called jQuery’s get method with the same URL then we'd get back the data we stubbed out. A key to remember is that you do need to tell the server to respond as we did immediately after we called the get method. And finally we need to restore the server when we are done.

Fake Server Unit Test


Let’s take this technique and add it to our twitter unit test.


In our before hook we create the server and match the resource that our twitter app will be calling and pass back the data we want to stub out. Then we unit test out the getTweets method as we did before, but things don't work out as we expect! Why is that? Well, it is because we are using JSONP as our jQuery ajax datatype. The way JSONP works is that it isn't actually using XMLHttpRequest as a typical Ajax call does. Instead JSONP uses some trickery of injecting a dynamic script tag on your page and a bunch of other things that jQuery tries to hide from you for simplicities sake.

So, in this case using the fake server won't help us. It would be better if we used a stub like we did in the last example.

Conclusion


Hopefully you can see that Sinon.js is a great utility library to help make unit testing a much more effective and terse experience. You'll probably more often than not find yourself making spies and stubs much more often than mocks, but that is really up to how you approach unit testing.

If you enjoyed this content you can get more from my recent Pluralsight course entitled: Front-End First: Testing and Prototyping JavaScript Apps where I cover an introduction to Unit Testing, look at various examples of hard to test code and introduce the following libraries and tools... Mocha, Grunt, Mockjax, amplify.request, mockJSON, etc...

Wednesday, May 15, 2013

Testing and Prototyping JavaScript Applications


I'm pleased to announce that I've finished my first course for Pluralsight entitled Front-End First: Testing and Prototyping JavaScript Apps.

Years ago it was common for the back-end to have code coverage, but having unit tests for client-side JavaScript was difficult, cumbersome, and rare. Thankfully, today that is no longer the case. By using various tools and libraries such as Mocha, Sinon.js, and GruntJS you can easily provide code coverage for your front-end as well.

Historically a front-end developer had to wait until the back-end was complete before they could start truly building a functional User Interface. Thankfully today there are libraries such as Mockjax, AmplifyJS, and mockJSON that can enable you to simulate the interactions with the back-end before its even complete. By doing so, this enables a front-end developer to work independently from the back-end and allows both teams to efficiently work within their speciality.


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!