Showing posts with label jQuery. Show all posts
Showing posts with label jQuery. Show all posts
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...
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.
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.
Posted by
Test
at
12:12 AM
0
comments
Labels:
AmplifyJS,
JavaScript,
jQuery,
Pluralsight,
Unit Testing
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
- Red Bird - IIFE
- Blue Bird - Events
- Yellow Bird - RequireJS
- Black Bird - Backbone
- White Bird - Linting
- Green Bird - Mocking
- Orange Bird - Templating
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.
- JavaScript Design Patterns by Joe Zim (@JoeZimJS)
- Understanding Design Patterns in JavaScript by Tilo Mitra (@tilomitra)
- Learning JavaScript Design Patterns by Addy Osmani (@addyosmani)
- JS Patterns by Shi Chuan (@shichuan)
- JavaScript Patterns by Stoyan Stefanov (@xyz)
- JavaScript: The Good Parts by Douglas Crockford
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!
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
- Red Bird - IIFE
- Blue Bird - Events
- Yellow Bird - RequireJS
- Black Bird - Backbone
- White Bird - Linting
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, March 28, 2013
Angry Birds of JavaScript: Blue Bird - Events
Introduction
A diabolical herd of pigs stole all of the front-end architecture from an innocent flock of birds and now they want it back!
A team of special agent hero birds will attack those despicable pigs until they recover what is rightfully theirs, front-end JavaScript architecture!
Will the birds be successful in the end? Will they defeat their bacon flavored foe? Let's find out together in another nail biting episode of Angry Birds of JavaScript!
Check out the series introduction post for a list of all the birds and their attack powers.
Previous Attacks
Blue Bird Attack

In this post we will take a look at the Blue Bird who triggers events and messages that scatter to infiltrate the pig's castle. Slowly, one by one, the birds will take back what it theirs to keep!
What Was Stolen by the Pigs?
The birds used to build their web applications with components having hard dependencies on each-other. They eventually started to learn to reduce tight coupling by introducing events and messages. Unfortunately the pigs, during their invasion, stole the birds' observer secrets.One of the blue birds has been tasked with taking back what has been stolen and restore loose coupling components.
Sample Application
In order to unpack the need for messages we will look at the following web application to search for movies from Netflix. We will uncover how this application was originally coded and then refactor along the way.
Tightly Coupled Code
The first version of the above application was coded using the following JavaScript code. Take a look at the code and let it start to sink in for a little bit. It may be painful, but please bar with me for a moment ;)
The above code sample is a typical jQuery example that you can find across the internet. The snippet works, but there is a lot of different things happening all in the same place. You can find event handling, data retrieval, and data manipulation all mixed together. You can imagine that over time this code might continue to grow and grow and become more and more prone for errors.
Before we get too far, let's take a side trip and look at what messages are and what types exist.
Types of Messages
Observer Events
An observer event is probably one that you are most used to if you are familiar with front-end web development. In relation to the DOM you can think of this as adding event handlers to an element. The element has a direct reference to the callbacks that will be invoked when the event type occurs.
Example
Mediated Events
A mediated event or message has become more common the last several years in front-end web development. The main idea here is that there is another entity that keeps track of publishing and subscribing of messages. The main difference between this and Observer events is that Mediated events aren't tied directly to the subject that invoked it.
Example
Implementations
There are several libraries out there that facilitate mediated events. The following is a list of various libraries that you may want to choose from. My recommendation is that you look at Jim's postal.js library.
- Ben Alman's (@cowboy) Tiny jQuery Pub/Sub library
- Peter Higgin's (@phiggins) pubsub.js library
- Jim Cowart's (@ifandelse) postal.js library ← Recommended
- Dustin Diaz's (@ded) reqwest library
- appendTo's (@appendTo) AmplifyJS Pub/Sub component
Hybrid Events
There is another type of event that is sort of a hybrid between observer and mediated. This type looks like a mediated event, but if you look hard enough there you could actually trace the origin of the event back to the original subject. A good example of this is jQuery's delegated event model. Delegated events are great, but it is based on the concept of events bubbling up the DOM and therefore we can trace where it came from.
Example
By the way, I don't recommend using the
$._data() method as it is undocumented and therefore not guaranteed that it will be available in future versions of jQuery. It is an internal helper method that jQuery currently uses under the covers. However, I did want to show you that there is a way to poke around and get at information that the subscriber shouldn't have in a real "mediated event", which is why I'm calling it a hybrid event. Don't get me wrong, I love jQuery's delegated events. I just wanted to show how it is a hybrid of the two above concepts.Which One Should Be Used?
That information is all fine and good, but what type of event/message should you be using and when? That is a great question and one that my friend Jim addressed in a recent post that he wrote. The following is a quote from his article...
"...use observer 'locally', inside a component, mediator 'remotely' between components. No matter what, be ready to use both in tandem.' --Jim Cowart
Jim recommends using observer events (jQuery's
.on() method) when communicating within a module and to use mediated events (postal.js) when communicating between modules.Another technique that Jim brings up in his article is to promote observer events into mediated events, which gives you the both of both worlds. He has some nice examples showing how that could look. I encourage you to take a look at his article referenced below in bold.
Additional Resources
If you are interesting in more information about the above concepts you may consider looking through some of the following resources about events and messaging.
- Jim Cowart's (@ifandelse) Client-side Messaging Essentials article
- Addy Osmani's (@addyosmani) Understanding the Publish/Subscribe Pattern for Greater JavaScript Scalability article
- Rebecca Murphey's (@rmurphey) Loose Coupling with the pubsub Plugin screencast
Loosely Coupled Code
I was tempted to write the following code using Backbone.js or create constructor functions, but in order to keep it simple and convey the idea of messaging I tried to remove all of that. So, this probably isn't what you'd have in your code-base, but hopefully it gets the point across.
Attack!
The following is a simple Angry Birds clone using boxbox, a framework for the box2dweb JavaScript physics library, written by Bocoup's Greg Smith.
Press thespace barto launch the Red Bird and you can also use the arrow keys. If it takes you too long to destroy the pigs you might want to consider pressing thespace barseveral times ;)

Conclusion
Using events and messages across your web application can help with communication. Events allow a component to communicate with itself and messages can enable other components to listen in without having a hard dependency.
There are many other front-end architecture techniques that have been stolen by the pigs. Tune in next time as the next Angry Bird takes its revenge! Dun, dun, daaaaaaa!
Tuesday, February 12, 2013
jQuery Object Quacks like an Array Duck
jQuery Array-like Object
I'm sure you've heard of the old saying, "If it looks like a duck, swims like a duck, and quacks like a duck, then it probably is a duck".
Well, a simular statement could be said about the
jQuery Object. If the jQuery Object looks like an array, indexes like an array, console.logs like an array, then it probably is an array... err, well, but in this case it's NOT an array!Let's unpack this a little more and see what sense we can make out of it. The following snippet of code invokes the
jQuery Function and performs a selection from the DOM and then accesses the returned jQuery Object to locate the DOM element at index 2, which feels an awful lot like an array.Upon further examination in the console the
jQuery Object is indeed an object (not an array) as indicated by the $.type() utility method.Note: You might notice that I am using the lesser known$.type()utility method to determine the type of the variable. I am not using thetypeofoperator because it evaluates to "object" for both arrays and objects. The$.type()method returns much more useful data http://api.jquery.com/jquery.type/
Something of interest in the above screenshot is the grayed out
__proto__ property. That is where all the jQuery goodness (functionality) can be found such as .fadeOut(), .on(), .addClass(), and all the other methods jQuery provides.After some digging in the jQuery source code I came across the following
merge method where the array results of the DOM selection gets copied over to the jQuery Object. In addition to mapping over these values jQuery also provides a .length property and a .splice() method which enables itself to mimic an array.Making a Custom Array-like Object
So, what about making our own custom array-like object!?! The following small snippet of JavaScript defines an object and then assigns a set of key/value pairs. In order to mimic an array we need to add a
.length property and expose a .splice() method borrowed from the array. The following is a screenshot of what is console.logged after executing the above code snippet. You will see that our
array_like object is treated as if it were an array just the like jQuery Object... yay!Note: If we take off the.lengthproperty or the.splice()method then the custom object will no longer appear as an array in the console. They are both necessary.
Conclusion
So, inductive reasoning might be a good thing most of the time, but in this case the Duck Test failed us. You can play around with the code snippets above by looking at the following JSFiddle.
Tuesday, February 05, 2013
Animating a Twitter BootStrap Icon with CSS3
Introduction
So, I was already using Twitter Bootstrap on a project recently and I had a refresh icon that I wanted to use a button. The markup for my icon looked very much like the following snippet...
The previous markup renders as the following...
That is all fine and dandy, however, I thought it would be neat if the refresh icon would rotate when the clicked until that action was complete.
To implement this feature I decided to use a CSS3 animation.
Note: At the time of writing this CSS3 animation is currently supported in IE10, Firefox 16+, Chrome 23+, Safari 5.1+, Opera 12.1+, iOS 3.2+, Android 2.1+, & Blackberry 7.0+ Reference: Can I Use?
CSS3 Animation
If you don't already know about CSS3 Animation you can pick up a primer at the following locations...
I ended up using the following CSS to get the animation to work...
Note: You may have noticed that I'm not using vendor prefixes in the above CSS. For this demo I am using only the standard prefix-free styles and using Lea Verou's -prefix-free library to dynamically add the vendor prefixed styles at runtime. Now, you may or may not want to use this library for production, but it sure makes it nice for blog posts and jsFiddles!
The above CSS defines a class named
icon-refresh-animate that assigns the animation, how long it should take, how many times it should iterate, and what type of algorithm to use. The class references the rotateThis keyframes which defines what the beginning and end state of the animation should look like. In this case the animation will rotate the element from 0 degrees to 360 degrees.Once I got the CSS3 situated, I moved on to writing some JavaScript to wire up the animation. The following code snippet adds the
icon-refresh-animation class to the icon when the anchor is clicked. Once the class has been added the animation begins. Then the code kicks off a window.setTimeout to simulate some kind of asynchronous action and when complete the class is removed, therefore stoping the animation.You can interact with the final solution in the following jsFiddle. You'll need to click the icon in order to kick off the 2 second animation.
Conclusion
Now, get going and get your baby ninja talents to work. Okay, I admit animated GIFs are cool, but not for rotating your icons ;)
Monday, February 04, 2013
FluentConf Advanced jQuery Training & Session
FluentConf 2013
Last year I was unable to attend FluentConf, but I'm honored to be on the Program Committee this year. In addition I'll be leading a 3 hour Advanced jQuery workshop and presenting a session on JavaScript.
Training Workshop
Advanced jQuery Techniques
On Tuesday, 05/28/2013 at 9:00am I will lead a workshop on Advanced jQuery Techniques. This workshop will be last 3 hours long and will contain a combination of both lecture and lab.
If you would like to attend this workshop you can add it to your schedule. You can view all of the other workshops from the FluentConf website.
Join appendTo’s Elijah Manor for a dive into advanced topics surrounding the front-end with jQuery. Utilize the jQuery library in the context of large-scale applications by learning how to dramatically improve performance, increase maintainability and reusability, and write cleaner and more concise code. Learn how to adopt a style that is maintainable and scalable while keeping simplicity as a core tenant for successful web development.
JavaScript Session
Angry Birds of Modern JavaScript Development
On Wednesday, 05/29/2013 at 1:45pm I will present a session titled Angry Birds of Modern JavaScript Development.
This is not your ordinary session, I've tried to mix things up by having each Angry Bird represent an area of JavaScript along with its strengths. Some topics covered include code organization, events and messaging, MV* frameworks, prototyping and mocking, design patterns, linting, and build systems. The goal is to defeat the pigs and by doing so produce highly tested quality JavaScript code.
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 these despicable pigs until they recover what is rightfully theirs, front-end architecture!
The Red Birds attacks with the force of their trusty IIFE, the basic building block of all privacy. The Blue Bird follows in his footsteps and triggers events and messages that scatter to infiltrate the pig’s castle. The Yellow Bird comes with a Require.JS speed booster and dynamically injects scripts against those pesky swine. The Black Bird is soon to follow and he provides a much more organized approach to fighting these porkers and introduces the Backbone.js bomb to their dismay. The White Bird appears to be seemingly harmless, but when it pulls out it’s strict coding style and bursts of quality checks the hogs are sure to squeal. The Green Bird can reach all of those hard to reach places and will mock and spy those stealing swine right where it hurts! The Orange Bird starts out small with a simple template, but then expands itself into a DOM blast that will surely send the message that the birds mean business. The Big Brother is not too far behind and he is pulling out the big guns with his finite state machine and other proven design patterns of destruction. The Mighty Eagle pulls up the ranks with a 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 be vanquished foe.
appendTo Virtual Live Trainings
In addition to the previous FluentConf workshop and session I also lead Virtual Live Trainings for appendTo.
If your company is interested in a private remote training experience on JavaScript, jQuery, Backbone.js, Underscore.js, RequireJS, or other web technologies please e-mail training@appendto.com for more information.
Here are some of the benefits of a Virtual Live Training (VLT)
- Virtual Live Trainings can be located worldwide. I've performed numerous trainings both in the United States and overseas.
- Virtual Live Trainings are cheaper than our On-Site Trainings because there is no additional cost for travel or hotel fees.
- Virtual Live Trainings are well suited for 1/2 day trainings over a week duration enabling the students to gradually absorb the knowledge and also remain productive at their day job.
- Virtual Live Trainings can be scheduled quicker than an On-Site Training since there is no travel involved.
- Virtual Live Trainings get the same content and labs as an On-Site Training and to make it feel more personable I stream video of myself as well as my screen.
Tuesday, January 29, 2013
Yo dawg, I herd you like loops, so jQuery put a loop in your code

Do You Know When You Are Looping in jQuery?
A common misunderstanding I see when looking at jQuery code is a lack of understanding about loops.
Most developers seem to grok the
.each() method, but that can be both a good and a bad thing. It is important to know the difference between an Implicit Loop and an Explicit Loop.
Implicit Loops
The following code snippet is something that you would typically see from a jQuery developer. You are probably aware of the "Find something, Do something" mentality of jQuery. The code first queries the DOM for all elements that have the
widget class and then jQuery proceeds to implicitly loop over all of the elements matching the query and adds the highlight class.Explicit Loops
An explicit loop in jQuery is much more obvious. The code for the loop is visible via the
.each method. This is pretty straight forward and typically developers understand that there could be performance issues for any code inside the .each loop.Indications of Confusion
You can start to tell if a developer doesn't realize the different between implicit and explicit loops if you start to see something like the following code snippet.
In this example there is no reason for using the
.each method because there was nothing inside of the loop that is unique. A simple implicit loop, like the following snippet, would have been sufficient. 
Method Overloads
Knowing about implicit loops also sheds some light of the following situation.
In the following snippet of code jQuery is looping over the matches elements twice (once to change the color and a second time to change the font-size).
If you needed to write code similar to the previous, you could do something like the following instead and use the "overloaded"
.css method that takes an object containing the key/value pairs you wish to apply. It might seem like the above snippet is slower than the following, but when it comes down to it they are about the same speed. I tend to recommend the last snippet as it is cleaner and more flexible down the road as you can pass in a variable containing all your options.
As a side note, it is preferable to use the.addClass()/.removeClass()/.toggleClass()methods instead of the.css()method to manipulate your elements unless you need to change their width/height/position/etc. The output of the.css()method gets attached to thestyleattribute of your element. The browser is highly optimized to deal with CSS classes and also whoever is maintaining will thank you for using classes instead of hardcoding style in your code.
Conclusion
Although these concepts may seem very basic, I often run across code that doesn't require an
.each method. It is helpful knowing some of these under the cover concepts. I hope you found it insightful.
Monday, January 28, 2013
Beginner HTML5, JavaScript, jQuery, Backbone, and CSS3 Resources
A Beginner's Journey
I was recently approached by someone at a .NET User Group about how to get started in HTML5, JavaScript, jQuery, CSS3, etc... The developer's primary background was writing thick client Windows applications. I figured the best place to start is to focus on the bare essentials and then work up to more advanced concepts and resources. I started to respond to the developer in an e-mail, but then I remembered what Scott Hanselman said in a recent post and video ...
"Instead, consider writing a blog post or adding to a wiki with your keystrokes, then emailing the link to the original emailer." --Scott Hanselman
So, I decided to make this blog post for the developer and also for anyone else who may be interested in similar resources.
HTML5
So, it is pretty obvious that you are going to need to learn HTML5 if you are doing to do front-end web development. From my experience most developers regardless of their language of choice know the basics of HTML. What they may or may not know are all the newer semantic tags, cross-browser tricks, and native JavaScript APIs.
There is plenty to learn in HTML5 without getting into the JavaScript APIs just yet. Once you learn JavaScript and feel comfortable in it, that may be the best time to tackle topics such as Geolocation, Web Sockets, Canvas, IndexDB, Web Workers, etc...
Resources
- HTML5 for Web Developers API
- HTML5 Semantics by Bruce Lawson Blog
- Semantics in HTML5 by John Allsopp Blog
- Designing a blog with HTML5 by Bruce Lawson Blog
- HTML5 Rocks Tutorials Blog
- Move the Web Forwards Misc
- HTML5 Doctor Blog
- HTML5 Specification API
- Dive Into HTML5 by Mark Pilgrim Book Free
JavaScript
Even if you think you know JavaScript it might behoove you to go back and learn it from the beginning. A common danger is that developers think it looks just like their back-end language of choice (C, C++, C#, or Java) that they don't invest time to learn how it is different.
JavaScript is a dynamic and functional language, which is considerably different than C# or Java for example. So, please take your time and pick up the language. If you don't learn it appropriately you will invariably run into barriers down the road due to lack of understanding.
Resources
- Eloquent JavaScript by Marijn Haverbeke Book Free
- JavaScript Enlightenment by Cody Lindley Book Free
- JavaScript: The Good Parts by Douglas Crockford Book Paid
- Professional JavaScript for Web Developers by Nicholas Zakas Book Paid
- What to Read to Get Up to Speed in JavaScript by Rey Bango Blog
- Learn jQuery & JavaScript for free by appendTo Video
jQuery
The jQuery library has been around for several years and has catapulted as one of the most used tools in the web developer's belt. The reason for its vast usage is that it solves many of the cross-browser issues that creep up during development. The library is popular for both web developers and web designers. The community around jQuery is amazing and there are tons of jQuery plugins to choose from.
Resources
- jQuery API API
- jQuery Plugin Repository Library
- Learn jQuery & JavaScript for free by appendTo Video
- jQuery Fundamentals by Bocoup Book Free
- Learn jQuery in 30 Days by NETTUTS Video Free
Backbone.js
If you find yourself writing more and more JavaScript and jQuery then you may want to consider picking up Backbone.js to help you organize your web application. This library is also a great fit for Single Page Applications (SPA). Backbone.js uses the familiar MVC/MVP concepts of Models, Collections, Views, and Routers. In addition there is a nice Event model, History support, and a Sync mechanism. The community for Backbone.js is also very large and you can find many extensions and plugins to fit your needs.
Resources
- Backbone.js API API
- Annotated Backbone.js Code API
- Backbone Extensions, Plugins, & Resources Library
- Backbone Boilerplate Misc
- Backbone Fundamentals eBook by Addy Osmani Book Free
- Peep Code: Backbone.js Video Series by Geoffery Grosenbach and David Goodlad Video Paid
- The Pragmatic Bookshelf: Hands-on Backbone.js by Derick Bailey Video Paid
- Backbone.js Screencasts by Joey Beninghove Video Paid
- Pluralsight: Backbone.js Fundamentals by Liam McLennan Video Paid
- The Skinny on BackboneJS by Ben Howdle Blog
- Backbone Tutorials Misc
- Backbone.js Tutorials via Nettuts Blog
- Exploring Backbone.js Series by Jack Franklin Blog
CSS3
You may or may not have experience with CSS. Brushing up on CSS concepts would be a good thing. If you already feed proficient at CSS1-2, then you should pick up CSS3 as well. A lot of features have been added recently that is in most modern browsers. There are many things that you can do in CSS3 now where you used to use JavaScript or custom images.
Resources
- Bulletproof Web Design Book
- Getting Started (CSS Tutorial) by MDN Wiki
- Mastering CSS Coding: Getting Started by Soh Tanaka Blog
- The 30 CSS Selectors you Must Memorize by Jeffrey Way Blog
- CSS3 Please Tool
- CSS3 Mastery Blog
- CSS Lint Tool
- CSS Comb Tool
Feature Detection
Inevitably you'll need to support browsers that don't support the native feature you are trying to use. Thankfully you can use Feature Detection to determine if the browser you are in implements that feature and if it doesn't then you can provide functionality to mimic that feature (a.k.a. a polyfill or shim).
Resources
- Modernizr Library
- HTML5 Please Tool
- HTML5 Cross Browser Polyfills Library
- Can I Use? Tool
Responsive Web Design
Instead of implementing a different UI for mobile devices, tablets, and desktop browsers you can use responsive web design techniques to provide one experience that restructures the UI according to its size.
Resources
- Responsive Web Design by Ethan Marcotte Blog
- Responsive Web Design: What It Is and How To Use It by Kayla Knight Blog
- Design Process In The Responsive Age by Drew Clemens Blog
- Responsive Web Design Techniques, Tools and Design Strategies by Smashing Editorial Blog
Conclusion
Hopefully the above resources will get you started in your transition to front-end web development. There is a lot to learn, but it is an exciting space that changes frequently. Having a desire to learn is a good trait to have in this field.
If you have any resources that you think I missed please add them in the comments and I'll try to update the lists above if I think they are appropriate.
Tuesday, January 22, 2013
The 5 Emotional Stages of a jQuery Upgrade
The following post contains a emotional filled dialog between fictitious front-end developers "Frank Fowler" and "Mike Morris". In this drama filled exchange Frank decides to upgrade his current project to the latest jQuery release.
Sadness
Frank: Ahh man, I just saw that jQuery 1.9 was released. Too bad my current project is still using the 1.8.3 release.
Mike: Ohh bummer, sorry to hear that. I tested out the beta release of 1.9 that came out about a month ago and didn't have any issues.
Frank: Really!?! Sign... I wish I could upgrade. I don't know if I can convince my boss to invest the time to upgrade and staying on an older version makes me a little sad.
Fear
Mike: You might consider upgrading. They've fixed lots of bugs, enhanced CSS3 support, and added several new features.
Frank: I don't know. It is a big project and I don't know if I can risk all the extra testing. I'm glad that it worked out for you, but I may just have to stay on this old version while everybody else upgrades.
Mike: Frank, an upgrade shouldn't be so bad. The jQuery team does a good job outlining the change log and they have over 6000 unit tests to ensure quality over a suite of browsers.
Frank: Yeah, I guess you are right, but it is such a huge project. What if something goes wrong? Surely something will go wrong, right? I'm fearful that I won't be able to figure it out if there is an issue.
Mike: Well, it wouldn't hurt trying would it?
Frank: I guess you are right. Lets go head and give it a try.
Anger
Frank: Okay, I just added a reference to the jQuery CDN for the 1.9 release to my project. Here goes nothing...
Mike: So, how did it go?
Frank: Huh... WHAT!?! Nothing even works anymore! I knew I shouldn't have upgraded.
Mike: Well, what exactly is breaking?
Frank: Like I said, nothing works! What did jQuery do to this release? Are they trying to hurt the development community? The last version worked just fine for me. I don't know if I can trust this project anymore.
Shame
Mike: Now now, lets take a look at this together. Does your application use some of the features that jQuery deprecated?
Frank: What!?! Deprecated? Umm, well I don't know. When did they deprecate features?
Mike: A while back jQuery mentioned they were going to deprecate features like the
.live() method and .browser sniffing.Frank: Ohh, I guess I didn't realize that. Maybe I should have read the blog post release notes more thoroughly :(
Mike: Yeah, even though they deprecated those features jQuery hadn't removed them until the 1.9 release. So, maybe that is why some of your code is broken. I know you used to use
.live(). Did you change your .live() to use the new .on() method?Frank: Yeah, I never did switch to the new
.on() method that they added a while back and the application does do some sniffing using the $.browser object. So, I guess that means I won't be able to upgrade to the 1.9 release.Gladness
Mike: Ohh, no! The jQuery team planning for issues like this so they went ahead and put all of the removed deprecated features into a migration plugin in case you still need it. That way you can use the new stuff without having to immediately refactor your existing code. The idea is that you can slowly refactor as needed.
Frank: Really!?! Wow, that is so easy. Let me guess, that was explained in the release notes too?
Mike: Yep ;) No probably man, it happens. Now don't get me wrong there are some releases where some bugs are introduced in a major release, but they are usually found pretty quickly and a minor release comes out shortly after. However, with this particular issue there was a planned workaround.
Frank: Why looky there, I just applied the migration plugin and now my app is working as expected. Thanks for your help Mike.
Mike: I didn't really do anything, it was the jQuery core members... you should thank them ;)
Monday, October 08, 2012
Adding jQuery Deferred Support to AmplifyJS Request
A common feature request in the AmplifyJS Google Group is for the request component to support jQuery Deferreds.
Before I address that request, let me go into a little history about the AmplifyJS library. When AmplifyJS was announced there was a conscious decision to not have a hard dependency on jQuery and to make it library agnostic so that you could use Dojo, MooTools, YUI, or something else. So, the publish/subscribe and store components do not use jQuery at all. The default request type shipped with AmplifyJS does utilize jQuery AJAX, but you can just as easily create a new request type that uses Dojo, MooTools, etc.
Now that we have some of the history out of the way, let's get back to the feature request. Adding a tight dependency to jQuery's Deferreds implementation isn't in the AmplifyJS roadmap since it was written to be library agnostic. You can however, write your code such that the request component plays well with jQuery Deferreds if you so choose.
Back in October 2011 Eric Strathmeyer (@strathmeyer) answered a Google Group post regarding adding jQuery Deferreds support to amplify.requst. On of his suggestions was to manually wire up the
If you find yourself wanting to use jQuery Deferres often with amplify.request then you can use the following helper method that both Eric and Scott González (@scott_gonzalez) have recommended.
I thought some developers might want a syntax that looked more native when using jQuery Deferreds with amplify.request, so I went ahead and made the amplify-request-deferred plugin, base on the above work by Eric and Scott. To get started all you have to do is to include the plugin immediately after
Once you have the plugin included on your page, then you can use the plugin with syntax like the following...
Hopefully one of these solutions is sufficient for your needs. This is a very common request, but as I mentioned in the history section above the AmplifyJS library would rather be agnostic and not depend on any one library. I hope this is helpful to you. Thanks.
For a brief overview of the request component you can check out a post I recently titled Mocking jQuery AJAX with AmplifyJS Request. In addition there are many more features listed in the official documentation.A Little History of the Library
Before I address that request, let me go into a little history about the AmplifyJS library. When AmplifyJS was announced there was a conscious decision to not have a hard dependency on jQuery and to make it library agnostic so that you could use Dojo, MooTools, YUI, or something else. So, the publish/subscribe and store components do not use jQuery at all. The default request type shipped with AmplifyJS does utilize jQuery AJAX, but you can just as easily create a new request type that uses Dojo, MooTools, etc.
3 Ways to Provide jQuery Deferred Support
Now that we have some of the history out of the way, let's get back to the feature request. Adding a tight dependency to jQuery's Deferreds implementation isn't in the AmplifyJS roadmap since it was written to be library agnostic. You can however, write your code such that the request component plays well with jQuery Deferreds if you so choose.
1. Manually Wiring Up Deferreds
Back in October 2011 Eric Strathmeyer (@strathmeyer) answered a Google Group post regarding adding jQuery Deferreds support to amplify.requst. On of his suggestions was to manually wire up the
amplify.request with jQuery Deferreds for both the success and error callbacks as shown below.2. Using a Helper Function
If you find yourself wanting to use jQuery Deferres often with amplify.request then you can use the following helper method that both Eric and Scott González (@scott_gonzalez) have recommended.
3. Using the amplify-request-deferred Plugin
I thought some developers might want a syntax that looked more native when using jQuery Deferreds with amplify.request, so I went ahead and made the amplify-request-deferred plugin, base on the above work by Eric and Scott. To get started all you have to do is to include the plugin immediately after
amplify.request. Once you have the plugin included on your page, then you can use the plugin with syntax like the following...
Conclusion
Hopefully one of these solutions is sufficient for your needs. This is a very common request, but as I mentioned in the history section above the AmplifyJS library would rather be agnostic and not depend on any one library. I hope this is helpful to you. Thanks.
Monday, October 01, 2012
Don't Initialize All the Things in jQuery.ready()
One of the first impressions a user gets is loading your web application for the first time. Users don't have a high tolerance when it comes to page speed. They want to see something almost immediately and then be able to start interacting with your web site shortly after.
If your website utilizes JavaScript and jQuery, which many web sites do, it is very tempting to pre-initialize all of your logic (plugins, widgets, modules, event handlers, etc) in order for them to respond as fast as possible. Unfortunately, initializing ALL THE THINGS during page load works against the user's goal of loading quickly. Instead of initializing everything when the page is ready you can instead wait to initialize portions of your application until they are needed.
The following examples will show two ways of initializing a date picker. The first way will "Initialize All the Things" and the other example will use the "Just-In-Time Initialize" principle.
In order to convey the idea I'm trying to explain it is probably easiest to show a code sample and then talk about what is happening. We will be using the following HTML for the markup that our code examples will be using.
The markup shows a simple form with various input elements. In the form we will have multiple date fields that we will want to initialize using the jQuery UI
The following
Let's unravel what the code is doing...
The following code snippet looks considerably different from the previous example, but the end result is the same and the Pros and Cons are quite different. See if you can spot out the differences.
You can view, run, and edit the above code sample from JsFiddle or you can interact with the embedded version below.
As we did in the previous example let's outline what is happening in the code and then we will examine the Pros and Cons of this technique.
You want to limit initializing all the things all the time. It can be helpful if you start to think about delaying initialization until the point when you need it or possibly right before. By doing so you can utilize the time right after jQuery is executed and not wait for DOM ready then you are able to use that precious time during page load. In addition you can have a crazy weird jQuery selector that still is fast. In our last code example above had a complicated selector, but it was very fast because it is only being tested against the one element that was focused on and not the whole DOM tree.
If your website utilizes JavaScript and jQuery, which many web sites do, it is very tempting to pre-initialize all of your logic (plugins, widgets, modules, event handlers, etc) in order for them to respond as fast as possible. Unfortunately, initializing ALL THE THINGS during page load works against the user's goal of loading quickly. Instead of initializing everything when the page is ready you can instead wait to initialize portions of your application until they are needed.
The following examples will show two ways of initializing a date picker. The first way will "Initialize All the Things" and the other example will use the "Just-In-Time Initialize" principle.
Example Markup
In order to convey the idea I'm trying to explain it is probably easiest to show a code sample and then talk about what is happening. We will be using the following HTML for the markup that our code examples will be using.
I am using Twitter Bootstrap to made the UI look more presentable and that is why you are seeing some extra classes attached to the above markup.
The markup shows a simple form with various input elements. In the form we will have multiple date fields that we will want to initialize using the jQuery UI
datepicker widget.Initialize All the Things
The following
jQuery code looks familiar to many snippets that you'll might find across the internet, in tutorials, and possibly in your web applications. I am using the small moment.js library to help with data manipulation. It is a handy date library that I think you'll find very compelling and rich with features.
Let's unravel what the code is doing...
- We wait until the document is ready before running the rest of our code.
- Once the DOM is ready, then select all the
inputelements on the page with thedateclass. - jQuery will implicitly iterate over it's internal collection of elements and initialize each one with the
datapickerjQuery UI widget.
Pros of this Technique
- When the user interacts with any of the
input.dateelements they will already be setup and therefore will respond extremely quick.
Cons of this Technique
- Your code has to wait until the DOM is ready before it can select the elements. It would be nice if you could utilize the time between when jQuery is executed and when the DOM is ready.
- The selector doesn't have any context so it is looking throughout the whole DOM looking for
inputelements with thedateclass. This would be considered a sub-optimal selector since there is no limit to the scope or context of what is being searched. - The code is initializing all the elements (implicit loop) whether you need them or not. Sure, the widgets are ready when you need them, but is all that up front code necessary?
- There is quite a bit of extra code running that isn't necessary yet before the page has even fully loaded. The affects the overall User Experience of page load, which is very key concern to users.
Just-In-Time Initialize
The following code snippet looks considerably different from the previous example, but the end result is the same and the Pros and Cons are quite different. See if you can spot out the differences.
You can view, run, and edit the above code sample from JsFiddle or you can interact with the embedded version below.
I am using the toastr library to show messages indicating when the elements were initialized. This library was created by Hans Fjällemark and John Papa.
As we did in the previous example let's outline what is happening in the code and then we will examine the Pros and Cons of this technique.
- We immediately set up an event handler to wait for User Input before initializing the
datepicker. This allows the code to run immediately afterjQueryhas been executed on the page before the DOM is even ready. We don't need the DOM to be ready because we are delegating our event to thedocumentcontext. - We aren't initializing all the
input.dateelement, but are only listening to thefocusevent. This event will propagate (a.k.a. bubble) up the DOM tree until it gets to thedocumentat which point jQuery will determine if the item focused on matches any of the metadata it has stored. This metadata match is surprisingly fast because it is only matching this "crazy" selector against the one DOM element that was focused on and not the whole DOM tree. - Our advanced selector is looking for
input.dateelement that doesn't have thehasDatepickerclass. If this is a match then that one DOM element will be initialized. After that point, if the element is focused on later the selector will no longer be a match because jQuery added thehasDatepickerclass during the it's widget creation.
Pros of this Technique
- Very fast page load speed because you are only adding an event handler to the
documentwith some metadata that will be used later - There is no jQuery selection being made on DOM ready
- There is no implicit looping going on to initialize the elements
- Only the elements that are about to be used are initialized so there is no wasteful code being executed
- The focused elements are only initialized once
- This technique will also work for dynamically added date pickers added to the DOM
Cons of this Technique
- There is some overhead of the focus event having to propagate up to the
documentand havingjQuerycheck the metadata to see if there are any matching selectors for the element in question, but this is mostly a wash since it is only testing one element.
Conclusion
You want to limit initializing all the things all the time. It can be helpful if you start to think about delaying initialization until the point when you need it or possibly right before. By doing so you can utilize the time right after jQuery is executed and not wait for DOM ready then you are able to use that precious time during page load. In addition you can have a crazy weird jQuery selector that still is fast. In our last code example above had a complicated selector, but it was very fast because it is only being tested against the one element that was focused on and not the whole DOM tree.
Much of this material was gleaned from an awesome series Doug Neiner has given at the past several jQuery Conferences entitled "Contextual jQuery" (video & slides). If you haven't already seen his talks or slides I highly encourage you to go through them.
Subscribe to:
Comments (Atom)




























