We’ve been seeing a sharp increase in the number of people interested in getting started with jQuery lately in our training and consulting business which is exciting since it’s such a great framework to use for client-side coding. If you’ve been fighting with cross-browser issues and want to make client-side development fun again then jQuery is a great way to go in my opinion.
One of the challenges with learning any new framework is knowing where to find documentation and good sources of examples. Although I normally rely on the standard documentation on the http://www.jQuery.com site, there are several other sources out there that can be helpful. Some of the sources are a bit dated, but they still provide a good way to find out more about core functionality. Here’s a quick list of the sites and extensions I’m aware of. If you know of others please let me know by adding a comment and I’ll update the list.
api.jquery.com
http://api.jquery.com
This is the main documentation site available for jQuery. It’s a great place to find details, but you’ll have to know where to look which can be frustrating sometimes for new developers.

jQuery API Search (Chrome Extension)
Get the extension here
This is a nice Chrome extension that adds jQuery API search support to Chrome’s omnibox (the URL/search textbox at the top of the browser). Simply type jq followed by a tab and then enter the function you’d like to get documentation on in the omnibox. The extension will search the APIs on the jQuery.com site and return matching results. Very handy….get it here.
jQuery API Browser (Chrome Extension)
Get the extension here
This Chrome extension provides a quick way to search through jQuery documentation without having to open up a webpage. It’s not completely up-to-date but is quick and efficient for finding information about most functions.

jQAPI.com
http://jqapi.com/
Provides a great way to pull up the official documentation using a simplified navigation mechanism. I like how clean the documentation is and how well the search and navigation scheme works. They also have an offline version available which is handy when you don’t have access to the network.

jQuery Source Viewer
http://james.padolsey.com/jquery/#v=git
This site provides a great way to see what’s happening inside the jQuery source code (a great way to learn various JavaScript tips and tricks). Simply type in the function you’d like to explore and the site will display the source code.

visualjQuery.net
http://visualjquery.net/
Another documentation site that provides a nice navigation scheme and clean view of the documentation. It’s a little outdated (covers jQuery 1.6).

api.jquery.com/browser
http://api.jquery.com/browser
This site provides some nice drill-down functionality to find out details about a particular function quickly and easily. It’s out dated but provides a quick way to find out about the core API functions.

api.jquery.com/visual
http://api.jquery.com/visual
This site is also a bit outdated, but if you’re looking to quickly find details on core functionality it makes it easy to drill-down into specific topics, see related functions, and then get details and samples about a given function.

If you’re interested in learning more about jQuery check out my jQuery Fundamentals course at Pluralsight.com.


Posted by dwahlin |
Fri, 20 Apr 2012 19:16:06 GMT |
Comments (3)
Previous Tips:
As the use of Ajax continues to grow in popularity it's worth taking the time to think through how Ajax calls are structured and used in an application especially if re-use and maintenance are important. If you analyze a lot of the Ajax code out there you'll likely find that calls to the server are scattered throughout scripts and pages. For example, if an Ajax call is made to get a list of jobs, a call is made directly in the script that needs the data. If another page/script needs the same type of data another Ajax call is made. This results in code duplication and complicates maintenance since Ajax calls aren't consolidated.
While there's certainly nothing wrong with this approach (it gets the job done after all), you can get better re-use out of your Ajax calls by consolidating them into JavaScript objects. In this post I'll talk about how Ajax calls can be consolidated using JavaScript patterns and describe the benefits this approach provides.
The Case for Consolidation
JavaScript libraries such as jQuery make it so easy to make Ajax calls that we often don't think much about the code being written and where it's being used. For example, consider the following code that's used to retrieve customers from a WCF service and update a page with the retrieved data:
$('#GetCustomersButton').click(function () {
$.getJSON('../CustomerService.svc/GetCustomers',
function (data) {
var cust = data.d[0];
$('#ID').text(cust.ID);
$('#FirstName').val(cust.FirstName);
$('#LastName').val(cust.LastName);
});
});
Although this code works fine, it can't be re-used across other pages that may also need customer data. If another page or script needs the same data then the getJSON() call will have to be re-written since the manner in which the returned data is processed will more than likely be different. In addition to this potential problem, the code is added into a script that may have completely different responsibilities that are unrelated to calling a service.
In the object-oriented world we strive to follow the single responsibility principle when designing classes to avoid duplication and provide better re-use. Following this same principle in JavaScript code makes a lot of sense and can lead to better re-use, simplified maintenance, and better overall organization of code in an application. By placing Ajax calls into a re-useable JavaScript object we can use them throughout an application more easily, minimize duplicate code, and provide a better maintenance story. Before jumping into how Ajax calls can be consolidated, let's review a key pattern called the Revealing Module Pattern that can be used to encapsulate JavaScript code.
Encapsulation with the Revealing Module Pattern
There are several different patterns that can be used to structure JavaScript code and provide a way for functions to be encapsulated inside of class-like structures (given that JavaScript doesn't officially support the concept of a class). One pattern that can be used is the Revealing Module Pattern. By using the pattern you can encapsulate variables and functions into an object, achieve re-use, simplify maintenance, and can also help avoid naming collisions. There are several other patterns such as the Prototype Pattern and Revealing Prototype Pattern that can be used (to name just two) but the Revealing Module Pattern provides a simple way to get started creating JavaScript objects that are similar in purpose to C# or Java classes.
The following code shows an example of some simple code that has no structure applied to it (I call it "Function Spaghetti Code"). With this approach variables and functions are scattered throughout a file with no rhyme or reason as to how they relate to each other. All of the variables and functions defined this way are automatically placed in the global scope which can lead to naming collisions.
var engine = 'V8';
function start() {
alert('Car started ' + engine + ' engine');
}
function stop() {
alert('Car stopped ' + engine + ' engine');
}
function turn() {
alert('Car turned')
}
Listing 1. Function-based JavaScript Code with no encapsulation.
Listing 2 shows this same code refactored to follow the Revealing Module Pattern. In this simple example the code is encapsulated in an object named car. Following this pattern allows the code to be organized, variables and functions to be taken out of the global scope, and a re-useable object to be defined that can be used in one or more pages or applications.
var Car = function (engine) {
var start = function () {
alert('Car started ' + engine + ' engine');
},
stop = function () {
alert('Car stopped ' + engine + ' engine');
},
turn = function () {
alert('Car turned');
};
return {
start: start,
stop: stop,
turn: turn
};
}('V8');
Listing 2. Organize functions in an object to provide encapsulation, re-use, easier maintenance, and to help avoid naming collisions.
Looking through the code in Listing 2 you'll see that 3 functions are defined including start(), stop(), and turn(). All three are publicly exposed to consumers using the return object that's defined (an object literal). Any functions not listed in the return object are inaccessible to consumers making them similar to private members in object-oriented languages. Since the car object is self-invoked (note the parenthesis at the end of Listing 2) you can call it directly using code such as the following:
car.start();
car.stop();
car.turn();
If you want to create a new instance of car the code in Listing 3 can be used instead of the code shown in Listing 2. Notice that the Car object starts with an upper-case character so that the consumer knows to create a new instance of the object to use it. This is a common convention being used more and more among JavaScript developers.
var Car = function (engine) {
var start = function () {
alert('Car started ' + engine + ' engine');
},
stop = function () {
alert('Car stopped ' + engine + ' engine');
},
turn = function () {
alert('Car turned');
};
return {
start: start,
stop: stop,
turn: turn
};
};
Listing 3. Using the Revealing Module Pattern to create a Car object that can be created using the "new" keyword.
To use the Car object the following code can be written:
var car = new Car('V8');
car.start();
car.stop();
car.turn();
If you only need one object in memory as an application is running the code shown in Listing 2 works well. If you need multiple instances of an object the self-invoking parenthesis can be removed as shown in Listing 3.
Now that you've seen how the Revealing Module Pattern can be used to structure JavaScript code, let's see how it can encapsulate Ajax functions into an object.
Consolidating Ajax Calls
A sample application named Account at a Glance (download it here – an image from the application is shown below) built to demonstrate several HTML5, jQuery, and general JavaScript concepts relies on the Revealing Module Pattern to consolidate Ajax calls into a single object that can be re-used throughout the application. By following this pattern, an Ajax call used to retrieve market quotes can be defined in one place and then called from other scripts that may need the data. This approach provides several benefits including more modular, re-useable, and maintainable code. If something changes with an Ajax call you can go to one place to make the core modifications rather than searching through multiple scripts and pages to find where changes need to be made.
To access market quote data in the application the following call could be made as data is needed in a given script:
$.getJSON('/DataService/GetQuote', { symbol: sym }, function (data) {
//process data here
});
Although this code works, it's much better from a re-use and maintenance standpoint to consolidate calls into an object. Listing 4 shows an example of an Ajax-specific object named dataService that the Account at a Glance application uses to retrieve different types of JSON data from the server.
var dataService = new function () {
var serviceBase = '/DataService/',
getAccount = function (acctNumber, callback) {
$.getJSON(serviceBase + 'GetAccount', { acctNumber: acctNumber },
function (data) {
callback(data);
});
},
getMarketIndexes = function (callback) {
$.getJSON(serviceBase + 'GetMarketIndexes', function (data) {
callback(data);
});
},
getQuote = function (sym, callback) {
$.getJSON(serviceBase + 'GetQuote', { symbol: sym }, function (data) {
callback(data);
});
},
getTickerQuotes = function (callback) {
$.getJSON(serviceBase + 'GetTickerQuotes', function (data) {
callback(data);
});
};
return {
getAccount: getAccount,
getMarketIndexes: getMarketIndexes,
getQuote: getQuote,
getTickerQuotes: getTickerQuotes
};
} ();
Listing 4. Consolidating Ajax calls into a dataService object.
The dataService object follows the Revealing Module Pattern discussed earlier to encapsulate the various functions. A single instance is created initially at runtime (the dataService function is self-invoked as the script initially loads) that exposes four functions responsible for getting account, market, quote, and ticker data from the server.
Looking through each function in the dataService object you'll notice that they all accept a callback parameter. Because each function is re-useable, it won't know how to handle the data that's retrieved from a given service - processing of data is unique to the caller of the function. As a result, each function in dataService allows the caller to pass a callback function that is invoked once the data returns from the service to the client. An example of calling the dataService object's getAccount() function is shown next:
dataService.getAccount(acctNumber, renderAccountTiles);
When the data is returned the getAccount() function will invoke the renderAccountTiles callback function shown in Listing 5.
renderAccountTiles = function (data) {
$('div.tile[id^="Account"]').each(function () {
sceneStateManager.renderTile(data, $(this), 500);
});
}
Listing 5. The renderAccountTiles() function handles data returned from the call to dataService.getAccount().
Note that a nested/inline callback function could be passed to getAccount() as well as shown next:
dataService.getAccount(acctNumber, function (data) {
//Process data here
});
Anytime a script in the application needs to retrieve data from the server a call can be made to one of the dataService object's functions and required parameters can be passed along with the callback. This technique provides a flexible way for Ajax functionality to be consolidated into an object while remaining flexible as far as callbacks go.
This technique can be applied to other parts of an application as well to create additional objects that encapsulate related variables and functions. By focusing on objects rather than functions you can more efficiently organize code in an application and achieve many of the benefits mentioned earlier such as better re-use and simplified maintenance. Eliminating Function Spaghetti Code is definitely a good thing.
If you'd like additional details about structuring JavaScript code or building an end-to-end application check out my Structuring JavaScript Code or Building an ASP.NET MVC, EF Code First, HTML5, and jQuery courses from Pluralsight.

Posted by dwahlin |
Thu, 19 Apr 2012 07:08:00 GMT |
Comments (16)
I had the opportunity to talk with Fritz Onion from Pluralsight about one of my recent courses titled Structuring JavaScript Code for one of their Meet the Author podcasts. We talked about why JavaScript patterns are important for building more re-useable and maintainable apps, pros and cons of different patterns, and how to go about picking a pattern as a project is started. The course provides a solid walk-through of converting what I call “Function Spaghetti Code” into more modular code that’s easier to maintain, more re-useable, and less susceptible to naming conflicts. Patterns covered in the course include the Prototype Pattern, Revealing Module Pattern, and Revealing Prototype Pattern along with several other tips and techniques that can be used.
Meet the Author: Dan Wahlin on Structuring JavaScript Code
The transcript from the podcast is shown below:
[Fritz] Hello, this is Fritz Onion with another Pluralsight author interview. Today we’re talking with Dan Wahlin about his new course, Structuring JavaScript Code. Hi, Dan, it’s good to have you with us today.
[Dan] Thanks for having me, Fritz.
[Fritz] So, Dan, your new course, which came out in December of 2011 called Structuring JavaScript Code, goes into several patterns of usage in JavaScript as well as ways of organizing your code and what struck me about it was all the different techniques you described for encapsulating your code. I was wondering if you could give us just a little insight into what your motivation was for creating this course and sort of why you decided to write it and record it.
[Dan] Sure. So, I got started with JavaScript back in the mid 90s. In fact, back in the days when browsers that most people haven’t heard of were out and we had JavaScript but it wasn’t great. I was on a project in the late 90s that was heavy, heavy JavaScript and we pretty much did what I call in the course function spaghetti code where you just have function after function, there’s no rhyme or reason to how those functions are structured, they just kind of flow and it’s a little bit hard to do maintenance on it, you really don’t get a lot of reuse as far as from an object perspective. And so coming from an object-oriented background in JAVA and C#, I wanted to put something together that highlighted kind of the new way if you will of writing JavaScript because most people start out just writing functions and there’s nothing with that, it works, but it’s definitely not a real reusable solution. So the course is really all about how to move from just kind of function after function after function to the world of more encapsulated code and more reusable and hopefully better maintenance in the process.
[Fritz] So I am sure a lot of people have had similar experiences with their JavaScript code and will be looking forward to seeing what types of patterns you’ve put forth. Now, a couple I noticed in your course one is you start off with the prototype pattern. Do you want to describe sort of what problem that solves and how you go about using it within JavaScript?
[Dan] Sure. So, the patterns that are covered such as the prototype pattern and the revealing module pattern just as two examples, you know, show these kind of three things that I harp on throughout the course of encapsulation, better maintenance, reuse, those types of things. The prototype pattern specifically though has a couple kind of pros over some of the other patterns and that is the ability to extend your code without touching source code and what I mean by that is let’s say you’re writing a library that you know either other teammates or other people just out there on the Internet in general are going to be using. With the prototype pattern, you can actually write your code in such a way that we’re leveraging the JavaScript property and by doing that now you can extend my code that I wrote without touching my source code script or you can even override my code and perform some new functionality. Again, without touching my code. And so you get kind of the benefit of the almost like inheritance or overriding in object oriented languages with this prototype pattern and it makes it kind of attractive that way definitely from a maintenance standpoint because, you know, you don’t want to modify a script I wrote because I might roll out version 2 and now you’d have to track where you change things and it gets a little tricky. So with this you just override those pieces or extend them and get that functionality and that’s kind of some of the benefits that that pattern offers out of the box.
[Fritz] And then the revealing module pattern, how does that differ from the prototype pattern and what problem does that solve differently?
[Dan] Yeah, so the prototype pattern and there’s another one that’s kind of really closely lined with revealing module pattern called the revealing prototype pattern and it also uses the prototype key word but it’s very similar to the one you just asked about the revealing module pattern.
[Fritz] Okay.
[Dan] This is a really popular one out there. In fact, we did a project for Microsoft that was very, very heavy JavaScript. It was an HMTL5 jQuery type app and we use this pattern for most of the structure if you will for the JavaScript code and what it does in a nutshell is allows you to get that encapsulation so you have really a single function wrapper that wraps all your other child functions but it gives you the ability to do public versus private members and this is kind of a sort of debate out there on the web. Some people feel that all JavaScript code should just be directly accessible and others kind of like to be able to hide their, truly their private stuff and a lot of people do that. You just put an underscore in front of your field or your variable name or your function name and that kind of is the defacto way to say hey, this is private. With the revealing module pattern you can do the equivalent of what objective oriented languages do and actually have private members that you literally can’t get to as an external consumer of the JavaScript code and then you can expose only those members that you want to be public. Now, you don’t get the benefit though of the prototype feature, which is I can’t easily extend the revealing module pattern type code if you don’t like something I’m doing, chances are you’re probably going to have to tweak my code to fix that because we’re not leveraging prototyping but in situations where you’re writing apps that are very specific to a given target app, you know, it’s not a library, it’s not going to be used in other apps all over the place, it’s a pattern I actually like a lot, it’s very simple to get going and then if you do like that public/private feature, it’s available to you.
[Fritz] Yeah, that’s interesting. So it’s almost, you can either go private by convention just by using a standard naming convention or you can actually enforce it by using the prototype pattern.
[Dan] Yeah, that’s exactly right.
[Fritz] So one of the things that I know I run across in JavaScript and I’m curious to get your take on is we do have all these different techniques of encapsulation and each one is really quite different when you’re using closures versus simply, you know, referencing member variables and adding them to your objects that the syntax changes with each pattern and the usage changes. So what would you recommend for people starting out in a brand new JavaScript project? Should they all sort of decide beforehand on what patterns they’re going to stick to or do you change it based on what part of the library you’re working on? I know that’s one of the points of confusion in this space.
[Dan] Yeah, it’s a great question. In fact, I just had a company ask me about that. So which one do I pick and, of course, there’s not one answer fits all.
[Fritz] Right.
[Dan] So it really depends what you just said is absolutely in my opinion correct, which is I think as a, especially if you’re on a team or even if you’re just an individual a team of one, you should go through and pick out which pattern for this particular project you think is best. Now if it were me, here’s kind of the way I think of it. If I were writing a let’s say base library that several web apps are going to use or even one, but I know that there’s going to be some pieces that I’m not really sure on right now as I’m writing I and I know people might want to hook in that and have some better extension points, then I would look at either the prototype pattern or the revealing prototype. Now, really just a real quick summation between the two the revealing prototype also gives you that public/private stuff like the revealing module pattern does whereas the prototype pattern does not but both of the prototype patterns do give you the benefit of that extension or that hook capability. So, if I were writing a library that I need people to override things or I’m not even sure what I need them to override, I want them to have that option, I’d probably pick a prototype, one of the prototype patterns. If I’m writing some code that is very unique to the app and it’s kind of a one off for this app which is what I think a lot of people are kind of in that mode as writing custom apps for customers, then my personal preference is the revealing module pattern you could always go with the module pattern as well which is very close but I think the revealing module patterns a little bit cleaner and we go through that in the course and explain kind of the syntax there and the differences.
[Fritz] Great, that makes a lot of sense.
[Fritz] I appreciate you taking the time, Dan, and I hope everyone takes a chance to look at your course and sort of make these decisions for themselves in their next JavaScript project. Dan’s course is, Structuring JavaScript Code and it’s available now in the Pluralsight Library. So, thank you very much, Dan.
[Dan] Thanks for having me again.

Posted by dwahlin |
Wed, 11 Apr 2012 06:00:57 GMT |
Comments (2)

It’s no surprise that mobile development is all the rage these days. With all of the new mobile devices being released nearly every day the ability for developers to deliver mobile solutions is more important than ever. Nearly every developer or company I’ve talked to recently about mobile development in training classes, at conferences, and on consulting projects says that they need to find a solution to get existing websites into the mobile space.
Although there are several different frameworks out there that can be used such as jQuery Mobile, Sencha Touch, jQTouch, and others, how do you test how your site renders on iOS, Android, Blackberry, Windows Phone, and the variety of mobile form factors out there? Although there are different virtual solutions that can be used including Electric Plum for iOS, emulators, browser plugins for resizing the laptop/desktop browser, and more, at some point you need to test on as many physical devices as possible. This can be extremely challenging and quite time consuming though especially when you consider that you have to manually enter URLs into devices and click links on each one to drill-down into sites.
Adobe Labs just released a product called Adobe Shadow (thanks to Kurt Sprinzl for letting me know about it) that significantly simplifies testing sites on physical devices, debugging problems you find, and even making live modifications to HTML and CSS content while viewing a site on the device to see how rendering changes. You can view a page in your laptop/desktop browser and have it automatically pushed to all of your devices without actually touching the device (a huge time saver). See a problem with a device? Locate it using the free Chrome extension, pull up inspection tools (based on the Chrome Developer tools) and make live changes through Chrome that appear on the respective device so that it’s easy to identify how problems can be resolved. I’ve been using Adobe Shadow and am very impressed with the amount of time saved and the different features that it offers. In the rest of the post I’ll walk through how to get it installed, get it started, and use it to view and debug pages.
Getting Adobe Shadow Installed
The following steps can be used to get Adobe Shadow installed:
1. Download and install Adobe Shadow on your laptop/desktop
2. Install the Adobe Shadow extension for Chrome
3. Install the Adobe Shadow app on all of your devices (you can find it in various app stores)
4. Connect your devices to Wifi. Make sure they’re on the same network that your laptop/desktop machine is on
Getting Adobe Shadow Started
Once Adobe Shadow is installed, you’ll need to get it running on your laptop/desktop and on all your mobile devices. The following steps walk through that process:
1. Start the Adobe Shadow application on your laptop/desktop
2. Start the Adobe Shadow app on each of your mobile devices
3. Locate the laptop/desktop name in the list that’s shown on each mobile device:

4. Select the laptop/desktop name and a passcode will be shown:

5. Open the Adobe Shadow Chrome extension on the laptop/desktop and enter the passcode for the given device:
Using Adobe Shadow to View and Modify Pages
Once Adobe Shadow is up and running on your laptop/desktop and on all of your mobile devices you can navigate to a page in Chrome on the laptop/desktop and it will automatically be pushed out to all connected mobile devices. If you have 5 mobile devices setup they’ll all navigate to the page displayed in Chrome (pretty awesome!). This makes it super easy to see how a given page looks on your iPad, Android device, etc. without having to touch the device itself. If you find a problem with a page on a device you can select the device in the Chrome Adobe Shadow extension on your laptop/desktop and select the remote inspector icon (it’s the < > icon):

This will pull up the Adobe Shadow remote debugging window which contains the standard Chrome Developer tool tabs such as Elements, Resources, Network, etc. Click on the Elements tab to see the HTML rendered for the target device and then drill into the respective HTML content, CSS styles, etc.
As HTML elements are selected in the Adobe Shadow debugging tool they’ll be highlighted on the device itself just like they would if you were debugging a page directly in Chrome with the developer tools. Here’s an example from my Android device that shows how the page looks on the device as I select different HTML elements on the laptop/desktop:
Conclusion
I’m really impressed with what I’ve to this point from Adobe Shadow. Controlling pages that display on devices directly from my laptop/desktop is a big time saver and the ability to remotely see changes made through the Chrome Developer Tools (on my laptop/desktop) really pushes the tool over the top. If you’re developing mobile applications it’s definitely something to check out. It’s currently free to download and use. For additional details check out the video below:

Posted by dwahlin |
Sun, 08 Apr 2012 03:06:36 GMT |
Comments (2)