New Book: jQuery, jQuery UI And jQuery Mobile
The book is divided into 4 sections - one each for jQuery core, UI and mobile libraries, and the last one to deal with plugins. Sections are broken into chapters covering various high-level scenarios. Each chapter includes several recipes and each recipe has one or more examples. The recipes map to practical activities that are performed by front-end developers, making it easier to figure out where the particular APIs are useful. The final section explains how to create reusable plugins, and also explores some common plugins and their usage.
InfoQ: Functions such as append() and appendTo() seem to do the same things but maybe with different syntax - is this just syntactic sugar or is there a stronger reason to have multiple ways to do the same thing in JQuery?
Phil Dutson: Those methods are mostly, as you say, "syntactic sugar". They both do the same thing. I like to separate them into how I am working. If I am working on inserting elements that are hard-coded or that tend to follow a static instance, I tend to use the .append() method. If I am working with an object that contains multiple elements or dynamic data, then I tend to use the .appendTo() method. What I do recommend doing is making up rules to using them and then sticking to them. Otherwise going back through your code and trying to reason why you used append() in one case and appendTo() in another will give you quite the headache.
InfoQ: You touch upon JSONP and mention the inherent security threats in using them for cross-site requests - could you explain more? Are there any valid alternatives?
Phil Dutson: When you use JSONP you are giving all of your trust to the server or web service that you are requesting data from. This means that if the server or web service starts sending out injected JSON data, you are passing it directly to the client making the request and the results may be disastrous. Many social platforms (including Google+, Twitter, and Facebook) have started to lock down their API services that return JSON objects and now require the client to use OAuth (or similar service) in order to get data. As for a valid alternative, you can always create a server-side proxy service that requests data and then parses the object before giving an object back. Or you can migrate your application to use OAuth and only interact with trusted servers and web services.
InfoQ: Is it possible to use jQuery UI with jQuery Mobile (for e.g. to create draggables on a mobile device)?
Phil Dutson: This is actually a fairly hot topic. The problem is that jQuery UI does not have support for touch events, and jQuery mobile does not have support for click-and-drag events. Some of this stems from jQuery Mobile binding a "drag" to a "swipe". I have not found a way yet to implement drag and drop with jQuery Mobile, however there are a couple of plugins that add touch support to jQuery UI. Touch-Punch and Mobile Drag and Drop are libraries that can be used in your web projects to allow drag and drop from touch devices. To be clear, Mobile Drag and Drop does not add drag and drop, but adds a tap-to-select and tap-to-target to move objects around in your web site/app.
InfoQ: What's the best way to treat touch-mouse hybrid devices such as laptops with touch enabled or new hardware such as Surface?
Phil Dutson: If you attempt to bind to both mouse events (click, mousedown, mouseup) and touch events (touchstart, touchmove, touchend) you will end up with what is referred to as a "ghost click". This happens because the touch even fires, and then the click event fires right behind hit. Sometimes this isn't a problem, while other times this can cause very strange and unexpected behavior (you can read more about this at Google developers). One of the best solutions I have found for this issue comes from Mathias Paumgarten. He has a simple snippet he uses that quite neatly takes care of this problem. You can view the snippet of his code.
InfoQ: You explain the usage of Promise objects and how they hide the internals - JQuery functions such as ajax() provide both the alternatives (using callbacks as well as using promise objects) - is there a reason to prefer one over the other?
Phil Dutson: Most of my Ajax work is done using the jQuery $.ajax() function. I also try to make sure that all of my projects are using at least version 1.6.4, because of this I am always playing with Promise interface (as it was built in to the $.ajax() method in version 1.5). Callbacks are usually quick and simple to use, however they can cause many hard to find errors when debugging code. This is especially prevalent when dealing with multiple Ajax calls to various social networks that you want to sync up into a web application.
InfoQ: You have dedicated an entire chapter on plugins provided by Bootstrap - why is that?
Phil Dutson: My original plan was actually to showcase the jQuery plugin repository, however it had been shut down and under construction (it actually just opened again in Jan 2013). I also wanted to feature plugins that would have active development and that would only get better. I thought about showing off the Foundation by Zurb library (I'm a huge fan of Orbit and Reveal), but the plugins they include had just been moved into the library as a whole instead of being offered separately. At the same time Bootstrap was having amazing success and was an exceptionally hot topic. I loved how they offered all of the plugins separately, in the case you didn't want to use the entire Bootstrap framework. Starting with Bootstrap gives any web developer a leg-up as it is still one of the power-house frameworks to get apps up and going in a minimal amount of time.
InfoQ: The JQuery team releases new versions quite fast, and is already at v1.9 - as a book author, do you consider this a challenge?
Phil Dutson: Any technology subject is a challenge due to the speed at which it evolves. Writing development books means digging through the alpha/nightly and beta releases of a project and spending time working and experimenting with code and how it behaves. There is always a bit of educated guessing as to what will make it into the final release and how it will end up working. With all of that being said, the jQuery team does an outstanding job of letting the public know what is on the chopping block and how soon. I'd say overall the worst part is handing in final copy and then waiting for the print copy to hit the shelves.
InfoQ: Network latency and bandwidth in mobiles can be much worse than the desktop counterparts - does JQuery help with that?
Phil Dutson: jQuery is not really a network optimizer, however the jQuery Mobile library is a fantastic way to deliver a site that has been built and optimized to work across a variety of devices and platforms at the minimum of required assets. As a bonus it handles things such as the difficulty of mouse and touch events, and gives you the freedom of a create-your-own template style engine. It even allows you to emulate swipes with a mouse. Another side bonus that is often overlooked with a popular framework like jQuery is the ability to load the jQuery library from a CDN location such as Google or Microsoft. If a user has already been to a site that uses the same CDN, then the browser will already have jQuery cached and ready for use with no extra overhead.
InfoQ: How do you abstract features that should go into separate plugins?
Phil Dutson: Personally I define what I am trying to accomplish and how often I am going to be using that task. For eCommerce sites that means deciding if I am going to use a specific type of modal window on every page, or a specialized gallery with a slider. If I am going to be doing a lot of repetitive tasks, then it should be considered for life as a plugin. The trickiest parts are finding out how much the plugin should do vs how customized you want the plugin to be. It doesn't do anyone any good if your plugin can take 30 parameters when it really only uses 2 of them.
InfoQ: Nodejs has a package for JQuery - could you give a couple of examples of how it can be useful to have JQuery on the Server-side?
Phil Dutson: jQuery is generally known for two things, easy DOM manipulation and selection, and the ease of use to perform Ajax functions. By including jQuery with Node.js you can use all of the selectors you are familiar with (along with insertion functions) and you can use all of the Ajax features. Of course you can get around without including jQuery, but for users who are new to Node.js and want something familiar to hold onto while they learn to use it, jQuery can ease some tension.
InfoQ: You have not covered unit testing in your book. What frameworks would you recommend for testing JQuery code?
Phil Dutson: I strongly recommend using QUnit for your unit testing. It is a very flexible framework that is even used by the jQuery team to unit test their code. If you have specific needs (such as working with node.js), you may want to look at some other frameworks such as jsTestDriver, Buster.js, and Yeti.
About the Book Author
Phil Dutson is the lead front-end developer for ICON Health and Fitness, one of the world's largest online fitness equipment retailers. There he specializes in creating seamless customer experiences across multiple browsers and platforms. He has worked on projects and solutions for NordicTrack, ProForm, Freemotion, Sears, Costco, Sam's Club and others. He was an original team member of the iFit project that integrated Google Maps into personalized workout creation and playback. Phil co-founded and currently manages "The E-Com DevBlog", a development blog focused on web development and solutions.
This article is based on the book, "jQuery, jQuery UI, and jQuery Mobile: Recipes and Examples", by Phil Dutson & Adriaan de Jonge, published by Pearson/Addison-Wesley Professional, Nov 2012, ISBN 0321822080, Copyright 2013 Pearson Education, Inc. For more info please visit the publisher website.