Skip to main content

Mobomo webinars-now on demand! | learn more.

Angularjs

 

Advanced Tools

Once you’ve mastered the layer of preprocessors and JavaScript frameworks (see part one for more info), you’ll be ready to take a look at some advanced UI development tools. In fact, you may have encountered any of these, to some degree, as you start working on larger web projects and applications.

Package Managers (prereq: Terminal)

As the number of dependencies in a project increases, it becomes increasingly important for developers to have ways to manage the download, inclusion, and versioning of an ever increasing number of dependencies. Package managers aim to solve this task by automating some or all of the tasks associated with managing the various assets and dependencies that may be included in any project you find yourself working on.

CodeKit is a GUI for searching for project dependencies (like jQuery, or Bootstrap), downloading those to your project folder, and managing the versioning/updates of the dependencies. CodeKit also includes a web server tool that allows you to host your project files locally without having to setup your own local web server, as well as tools to automate compilation of your Sass, CoffeeScript, etc. Neat.

Bower and NPM are command line tools that offer similar functionality. After being installed, you can download any asset from the Bower repository by running the bower install command. It also allows you to specify which versions of assets you’d like to use in your project, and automatically updates them all every time you run bower install. In this way, if one developer on your team makes an update to the version of jQuery you’ve included in your project, then checks that change into your shared repository, all other developers on the team can ensure consistency by simply updating their code base and then running bower install. CodeKit comes with Bower built-in, so you can install Bower packages directly from the CodeKit UI.

NPM (Node Package Manager) is a package manager that’s part of Node.js. Bower is actually a Node package, so after installing NPM, you can install Bower by simply running npm install bower. In addition to Bower, you can use NPM to install a plethora of assets (120,151 at the time of this writing), including tools I’ve already mentioned (Sass, CoffeeScript, Cordova) and have yet to mention (Grunt, Gulp, Browserify).

Bower and NPM may seem similar, but one of the biggest differences is that NPM handles nested dependencies (meaning dependencies can have dependencies), while Bower is a flat dependency tree (meaning that the user must resolve the dependencies; they’re not resolved automatically).

Browser Refreshing (prereq: Terminal)

In the olden days, to develop a website, you’d edit an HTML file, and refresh your browser to see the changes. With HTML, CSS and JS all being compiled in modern apps, it adds another layer. You’d have to save your source file (.sass, or .coffee, for example), compile it to CSS or JS, respectively, and then refresh your browser to see the changes. Browser refreshing tools allow developers to automate the refresh of the browser window when changes are saved to a source file.

Whether you’re using the LiveReload GUI or the command line tool Guard, you’ll need to install the LiveReload Chrome extension. This allows the browser to watch the underlying files for the page you’re viewing, and refreshes the browser window for you (without a noticeable full page refresh). For managing the process of watching source files and compiling them, you have three options: the LiveReload GUI, Guard, or Grunt.

Task Runners (prereq: JS, Terminal)

If you’re familiar with both JavaScript and the command line, having a look at task runners is a good idea. Even if you’re not, Chris Coyier has a great post titled Grunt for People Who Think Things like Grunt are Weird and Hard. Task runners allow web developers to automate an almost infinite number of tasks, like the aforementioned Sass and CoffeeScript compilation, concatenating a number of small JS files into a larger one for production, or compressing image files.

Gulp is the new kid on the block when it comes to task runners, but is very popular, and I’ve seen it used in many projects recently. Neither Grunt nor Gulp have GUIs, so you have to be proficient in JavaScript in order to use them. Their syntax is 100% JavaScript, so a healthy understanding of JS will go a long way here.

Testing (prereq: JS)

With the migration of many development methodologies typically exhibited on the backend into the front-end space in recent years, its no surprise that testing has come along for the ride. Testing in modern web apps has roots in writing tests for desktop applications, where the code would be compiled and packaged for production prior to being available to the public. Writing tests in JavaScript is mainly included in large scale projects, which use one of the JavaScript frameworks mentioned earlier. Generally, an app will have a combination of unit, integration, and e2e (shorthand for end-to-end) tests.

Karma is a unit test runner that will find all the unit tests you’ve written, open a browser, and run the tests in them. Its not partial to the framework the tests are written in; that is, you could write tests in Jasmine, or another testing framework, like Mocha, and Karma will run them. Jasmine is a testing framework, which is the actual syntax you write your tests in. Karma and Jasmine are the preferred method of testing AngularJS apps.

While unit tests are designed to test individual pieces of functionality, e2e tests are designed to test the entirety of your application. It’s truly amazing to watch Protractor fire up Chrome and perform every action you’ve defined in your tests. Protractor is the tool of choice for writing e2e tests for AngularJS.

Front-end Ops (prereq: JS)

Front-end Ops is new subset of front-end development that focus solely on the performance, builds & deployment, and general stability of modern web apps. The term was coined in an article in Smashing Magazine by Alex Sexton. As the front-end has increased in complexity, so too has the need for individuals solely focused on maintaining the health of the front-end.

Two tools used by front-end developers focusing on operations are RequireJS and Browserify. RequireJS is a tool for modularizing your JavaScript and CSS files, and optimizing them for deployment by minifying them, or removing comments, etc. AngularJS has dependency injection built in, so there’s no real requirement for RequireJS, and you can also handle a lot of the optimization with tools like Grunt. Browserify is much newer than RequireJS, and I honestly haven’t spent that much time with it yet, but I expect to start seeing it on a lot more projects.

It should be noted that these tools will eventually be phased out by the inclusion of module definition/injection in native JavaScript as part of the ES6 (ECMAScript 6) spec. They’ll be around for a while, and are currently in heavy use, but its worth keeping this in mind.

Looking Forward

Once you have mastery of many of the tools and technologies mentioned in this post, you’ll be ready for what’s coming down the modern web development pipeline: web components.

Web components are the future of how websites and web apps will be built. Web components allow modules or components to be truly independent, where the HTML, CSS and JS for each component is applied solely for that component, with no risk of conflicting with other components in the same site or app.

Polymer is a Google project that aims to make web components available today, so once you’re comfortable, start experimenting.

Hopefully this post has given you a good idea of the pieces that make up the modern front-end developer’s toolset. It may seem like a lot at first, but having a reference like this is a great place to start. If you get started today, you’ll be amazed at what you can create!

Any questions, thoughts, ideas? Send 'em our way!

Can't get enough? Well here you go!

  • An Introduction to Front-End Developer Tools
  • SEO for Single Page Applications
Categories
Author

Angularjs

Working on a project recently, I went through a process where I converted jQuery-style selectors and DOM manipulation to “The Angular Way”, and I thought I’d share my results.

This is one part of AngularJS I feel every web designer should become familiar with, as it shows how much easier it can be to understand JavaScript written by someone else when you use AngularJS. The reason AngularJS can be easier to understand is a result of its declarative nature, meaning you define click handlers right in your HTML, which in a larger project, can make it much easier to understand just what is going on under the hood.

This example will use a few simple buttons to show and hide content, and I’ll first demonstrate how we might accomplish this with jQuery, and then convert it to Angular. Suppose we were creating an app that allows users to create blog posts, and has three associated views. We might have the following buttons, and content sections:

<button id="btnCompose">Compose</button> <button id="btnPreview">Preview</button> <button id="btnPost">Post</button>  <div id="blogCompose">      <h1>Blog Compose</h1> </div> <div id="blogPreview" class="hide">      <h1>Blog Preview</h1> </div> <div id="blogPost" class="hide">      <h1>Blog Post</h1> </div> 

In jQuery, we would typically have to get all our buttons and assign a click handler that manages the display of the content (probably using a class attribute). Given the above HTML markup, our jQuery might look something like this:

$('button').on('click', function() {      var target = $(this).attr('id'); });  if (target == '#btnCompose') {      $('#blogCompose').removeClass('hide');      $('#blogPreview, #blogPost').addClass('hide'); } else if (target == '#btnPreview') {      $('#blogPreview').removeClass('hide');      $('#blogCompose, #blogPost').addClass('hide');  } else if (target == '#btnPost') {      $('#blogPost').removeClass('hide');      $('#blogCompose, #blogPreview').addClass('hide');  } 

We’re getting all the buttons on the page, and finding their id attribute. We then conditionally add or remove classes based on which button we’re clicking. The major drawback here is that it relies heavily on the structure of the HTML. If the HTML structure changes in the future, the jQuery selectors all have to be rewritten. Let’s take a look at how we might convert this to AngularJS.

First, here’s how we would change the markup:

<button id="btnCompose" ng-click="composeBtn()">Compose</button> <button id="btnPreview" ng-click="previewBtn()">Preview</button> <button id="btnPost" ng-click="postBtn()">Post</button>  <div id="blogCompose" ng-show="state.blogCompose">      <h1>Blog Compose</h1> </div> <div id="blogPreview" ng-show="state.blogPreview">      <h1>Blog Preview</h1> </div> <div id="blogPost" ng-show="state.blogPost">      <h1>Blog Post</h1> </div>  

You’ll notice two main changes here. First, we added what looks like an 'ng-click’ attribute to the buttons. ngClick is an Angular directive that calls a function in the associated controller. Next, we removed the classes from the content, and replaced with ngShow. ngShow is another Angular directive that shows or hides content based on its value. In this case, the values are state.sectionName. We’ll see what the state values are when we get to the JavaScript.

For now, take a moment and compare the jQuery and Angular HTML. The Angular markup gives you clues that clicking a button calls a function (and once you know more about Angular, you’ll know instinctively this function will live in the controller associated with this section of the DOM), while the jQuery buttons could have associated click handlers, but we don’t know without looking through the JavaScript, and we don’t have any assumptions about where those click handlers might reside in our JavaScript.

The “hide” classes we use with jQuery do communicate functionality, but can’t actually accomplish anything functionally. They’re more than likely associated with a CSS class with the display property set to “none”. The Angular ngShow directive allows us to define any number of conditions for the display of the content sections, and like ngClick, we know to look for this functionality in our associated controller.

Given this Angular markup, you might find the associated code in our controller for managing the application’s state:

//Defaults, page load $scope.state = {   blogCompose: true,   blogPreview: false,   blogPost: false }; //Manage state per button $scope.composeBtn = function () {   $scope.state.blogCompose = true;   $scope.state.blogPreview = false;   $scope.state.blogPost = false; };  $scope.previewBtn = function () {   $scope.state.blogCompose = false;   $scope.state.blogPreview = true;   $scope.state.blogPost = false; };  $scope.postBtn = function () {   $scope.state.blogCompose = false;   $scope.state.blogPreview = false;   $scope.state.blogPost = true; }; 

Here, we set the default state so the “compose" content is shown. This is what will be displayed when the app initially loads. We then manage the display of the content through functions assigned to the buttons. The “magic” here is that Angular handles assigning the functions to the buttons, and the state of the app. When we set the state property to either true or false, Angular knows to show or hide the associated content, via the ng-show directive in our markup.

The real beauty here is that we as developers aren’t responsible for parsing the DOM and making sure we have the right buttons or content sections based on the DOM structure. There’s no conditional logic in our JavaScript; we define a few variables and functions, and Angular takes care of the rest.

This is a very simple example, but you can imagine how it can make things easier as the size of your app scales and you have multiple developers changing your HTML markup. It not only makes it less error-prone, but its easier to understand what’s going on simply by reading the HTML or JavaScript, without having to actually run the app and interact with it.

I’ve created a functional JSFiddle demonstrating the AngularJS version, if you’re interested in seeing it in action: http://jsfiddle.net/xna5odq7/1/

Categories
Author

My Twitter stream is abuzz today with the release of Rails 3.1. (You can view the Rails 3.1 Release Notes here). But of course, as the Rails community is comprised of an alarming level of passionate developers, a few diva-style outbursts are in the forecast. Though most of the responses are celebratory there are pockets of people reacting as though they are 5 years old and being forced to eat lima beans by their mothers. But unlike your mother, the Rails Core team isn't forcing you to eat anything. In fact, those who oppose the addition of CoffeeScript and SCSS can circumvent the changes in one step.

Most of the outcry was unleashed when DHH announced in April that CoffeeScript and SCSS would ship with Rails 3.1. CoffeeScript is a whitespace sensitive and expressive language that generates readable JavaScript code. SCSS is the new Sass syntax, and is an extension of CSS3. People have had some time to adjust to the idea since the announcement was made, but that hasn't stopped a vocal few from throwing a temper tantrum about it today. People can argue about its inclusion in Rails 3.1 for the next year (and they will) but what really matters is that the Rails contributors continue to identify and implement libraries and tools that advance Rails and make it more accessible.

Rails 3.1.0 introduces many changes, most of them widely anticipated by the community. The addition of jQuery was one of them and replaces Prototype as the default JavaScript library. jQuery was a crowd favorite since Prototype was more verbose and required the developer to keep track of more variable types. jQuery is more concise and most of its users boast a faster and more pleasant development experience. The addition of CoffeeScript and SCSS though, was not so widely celebrated.

Brent Collier, one of our Senior Engineers was put off by the growing negativity about the Rails 3.1 changes in his Twitter stream:

I don't understand the people complaining about the asset pipeline in Rails 3.1. I mean, if you don't like Sass/CoffeeScript, that's fine. You can still write normal CSS/JS. The only difference is that it goes in app/assets instead of public. It doesn't require devs to do anything different, other than putting files in a different directory. Yeah, 3.1 includes sass-rails and coffee-rails by default. If that ruins your day, you've got bigger problems."

Michael Bleigh feels that in debating CoffeeScript and SCSS in Rails 3.1 we're forgetting the important truth, which is that the asset pipeline is simply amazing:

Forget the drama about SCSS and CoffeeScript, the real story here is that Javascript and CSS are now first-class citizens in a Rails application. The ability to seamlessly integrate asset files from gems is going to change everything about how we build Rails applications.

Before the asset pipeline was announced, I was getting worried about the future of Rails. I saw that the future was to have much richer client-side language support, and Rails didn't necessarily do much to make that easier. Now I can't imagine using anything but Rails for a modern web app. As far as I'm concerned what Rails has done with the pipeline is a huge and important step towards keeping Rails on top for years to come.

Not liking SASS and Coffeescript just seems so pale in comparison to the awesome of first-class assets that I don't even know what to say.

Fortunately, despite some pockets of angry tweets, most people are expressing their gratitude to the Rails 3 team for their hard work. You can follow the stream of Rails 3.1 related tweets here.

Although we tend to be overly opinionated about our methodologies and tools, we're also adept at putting aside our differences in the spirit of ushering in intelligent progress. Today we're #rubythankful to the dedication of the Rails contributors who have worked diligently to make Rails the competitive framework that it is today. As Ruby and Rails devs our programming livelihood depends on Rails' ability to stay competitive and relevant in today's world. So we're offering a big thank you to those who have helped to support the language, the framework, the assets, and the community.

Maggie, our QA Manager recalls a chant her Mom would lead at the lunch table in her daycare when the kids turned up their noses at the food:

 

"YOU GET WHAT YOU GET AND YOU DON'T PITCH A FIT!"

 

All together now...

Categories
Author

Of all of the new tools that I've picked up using for development in the past six months, there is one that has come to stand above the others for its nearly universal utility. That tool is Guard.

Guard is a RubyGem but don't let that fool you into thinking it's only useful for Ruby projects. Guard is essentially an autotest for everything. It provides a general purpose set of tools for watching when files are changed in your project and taking action based on it. You can use it to do just about anything, but common uses will include:

  • Re-running automated tests after a file changes.
  • Automatically compiling scripts or assets for a project (e.g. minification).
  • Installing new dependencies that may be added to the project.

With a little creativity and a slight bit of Ruby coding, though, you can make your entire project's workflow run smoother and faster. It's like having a telepathic robot buddy who just goes around doing whatever you were about to do next without having to be told (except the first time).

Getting Started With Guard

Guard requires a basic Ruby setup. Once you have Ruby and RubyGems installed, simply run:

gem install guard 

This will get you started. If you want to make it easier for others to run your guards as well, you should also install Bundler to encapsulate the different guard gems you'll be using:

gem install bundler 

Once you have these installed, in the root of your project run:

guard init 

This will initialize a Guardfile in the project root that will be telling Guard what to do going forward. From here, you will want to install some of the Guard extension gems that let you quickly create automation for your project. Some of my favorites:

  • guard-rspec: Automatically run RSpec tests based on easy-to-customize patterns. I use this on almost every Ruby project these days.
  • guard-coffeescript: Compile Coffeescript into Javascript lickety-split. Even though Coffeescript has its own automatic build command with the -w option, I prefer Guard because it lets you define the configuration once and, in addition, run a single process for all of your project's automation.
  • guard-process: This is the guard for anything they haven't made a guard for yet. Using this you can quickly and easily run shell commands as soon as files change, giving you the ability to do almost anything.
  • guard-sass: Never write vanilla CSS again. Using Guard SASS you can automatically compile SASS giving you the full power of mixins, variables, and more for all your styles.

There's a full list of guards that include all kinds of magic (there's even guard-livereload that can automatically refresh your browser whenever you make a change to a project), and it's dead simple to create new Guard libraries if what you want isn't available (or you can just use guard-process).

Standing Guard

For any of the Guard gems you install, you can add them to your Guardfile by running:

guard init guardname 

Where guardname might be rspec or coffeescript, etc. That will fill your Guardfile with a basic implementation of the given guard and is usually enough for you to tweak the settings to your liking without further documentation.

There's a great example of using Guard for a big Rails project, but I'm not just using it for Ruby. I've used Guard on jQuery plugins, Node.js projects, even static websites that I've been building (more on that a little later).

To make it easier for others to jump into your project with Guard, it also helps to use Bundler to maintain a Gemfile that points to the various guards you're using for the specific project. Just run bundle init to get Bundler up and running then edit the file to look something like this:

source 'http://rubygems.org'  gem 'guard' gem 'guard-coffeescript' gem 'guard-process' 

Then run bundle install. Once your gems are installed and you've set up your Guardfile, just run:

bundle exec guard 

Guard will start up right away and your project now has some smooth automation action. Guard will even reload itself if you modify the Guardfile, so feel free to tweak as you go!

Guard in the Real World

I'm going to post just a couple examples of Guardfiles I've been using in my projects recently to give you an idea of its versatility.

Guarding a jQuery Plugin

Here's the Guardfile for Sketch.js, a jQuery plugin that I just released:

# Automatically build the source Coffeescript into the lib directory guard 'coffeescript', :input => 'src', :output => 'lib', :bare => true # Also automatically build the test Coffeescripts guard 'coffeescript', :input => 'test', :output => 'test', :bare => true  # Run Docco  guard 'process', :name => 'Docco', :command => 'docco src/sketch.coffee' do   watch %r{src/.+.coffee} end  # Copy the newly created lib file for minification. guard 'process', :name => 'Copy to min', :command => 'cp lib/sketch.js lib/sketch.min.js' do   watch %r{lib/sketch.js} end  # Use uglify.js to minify the Javascript for maximum smallness guard 'uglify', :destination_file => "lib/sketch.min.js" do   watch (%r{lib/sketch.min.js}) end 

This enabled my workflow to be instantaneous: I could immediately look at my work whether it was in my examples, my tests, or my documentation. Everything was immediately built and I never had to slow myself down with run and refresh cycles.

Guarding a Node.js Project

I've probably only scratched the surface here, but a simple Node.js project that I'm currently working on has this for a Guardfile:

guard 'coffeescript', :input => 'src', :output => '.', :bare => true  guard 'process', :name => 'NPM', :command => 'npm install' do   watch %r{package.json} end 

Notice that using guard-process I'm automatically installing new dependencies that may arise when the package.json file is altered.

Guarding a Static Website

I've come to really appreciate both Coffeescript and SASS as worthwhile abstractions, so even if I'm building something that's vanilla HTML I might have a Guardfile like this:

guard 'sass', :input => 'sass', :output => 'css' guard 'coffeescript', :input => 'coffeescripts', :output => 'javascripts' 

These are all basic examples, but that (to me) is the point: Guard is so simple to use and basic that you can drop it in every project you build. I've yet to run into something that I don't want to use Guard on.

Tip of the Iceberg

I've been expanding my usage of Guard into, well, everything that I'm working on. Thus far it's included Ruby, Javascript, and static HTML projects, but if I move on to other things Guard will be coming with me. For instance, I'd love to build a Guard to automatically recompile and run an Android application whenever the XML views change. The possibilities are limitless.

If you're not using Guard, give it a try on one of your current projects. I think you'll quickly find immense satisfaction in being able to simply cd into the project directory, run guard, and know that you are completely ready to roll. I'd like to see a Guardfile in every open source project I fork, every client project I clone...Guard is so useful that I simply want to be using it all the time. And that is the mark of a great tool.

Categories
Author

Do you know Chris Selmer? He’s one of the Senior Partners here at Intridea. He’s also a person that likes to run, even when nothing is chasing him. Its baffling, I know. Although, I guess I’m no better, as I’ve recently started going to the gym and picking things up just to put them down. Not my best decision. Regardless, Chris likes to run. Thanks to this little tidbit I was granted the fortune of attending Ruby Nation this month when Chris, who had already purchased a ticket to the conference, decided to sign up for a marathon to run an only-acceptable-while-in-a-car distance that very same weekend. Good for him, and good for me.

So what does this have to do with anything?

Well, it was at that conference that some things came together for me. By things, I mean some thoughts that had been lounging around in the back of my head for quite some time. I always knew they were there, but I hadn’t given them any attention. Until Ruby Nation that is. There were a handful of sessions that really brought these thoughts to the forefront.

The first session that caught my attention was our own Jerry Cheung’s presentation on Node.js (slides) where he gave a brief tour of Node and went over a handful of example scenarios where Node would work well alongside Rails. Then there was a Blake Mizerany's keynote in which he talked about being a polyglot, (someone who uses many languages). There was Chris Williams’ pirate-themed adventure called, “The Javascript Renaissance”. And finally, Ryan McGeary’s lightning talk on CoffeeScript (slides).

In addition to the conference, there were a number of things floating around the Twitterverse that also got my attention. There’s been an increasing trend of tweets either denouncing jQuery-only JS developers and/or their practices OR tweets praising some new JS tool/library. Another enticing find was a link to the talented Rebecca Murphey’s keynote presentation called, “The jQuery Divide”.

I’m guessing you’re probably starting to notice a theme here. It was the culmination of all these events that resulted this epiphany:

“Shit, I’m one of those jQuery-only jackasses. I need to do something about it.”

I tell myself that I write JS every day, but I don’t. I write jQuery. Don’t get me wrong, it gets the job done. But it never feels right. Now, jQuery and its DOM-centric approach (at least in common usage) aren’t all to blame. Its just as much my fault in that beyond the library, I know very little about the language. I intend to do something about it. I have a plan and I’m going to share it with you. First, here are my goals:

  • Gain a more thorough and detailed understanding of the JS language itself
  • Increase my exposure to the plethora of kick-ass new JS tools and libraries

Here’s how I plan to do it. First, with two books that have come highly recommended:

  • Javascript: The Good Parts by Douglas Crockford - I’ve had this for a while and read about half-way through it, but at the time I just wasn’t interested enough to finish it.
  • Javascript Patterns by Stoyan Stefanov

The second part of my plan is to spend a non-trivial amount of time with each of these:

  • Dojo - This seems to be the toolkit of choice when you want to move away from heavy DOM-dependency
  • Backbone.js - I like the idea of models and views on the front end.
  • Node.js - Having become so wrapped up in the Rails world, I’m interested in playing with a different web framework, or in this case, http parser.
  • Coffeescript - I know, I know. Its an abstraction from JS, but whatever. It's new and people seem to really like it or hate it (see the recent Rails 3.1 controversy) so it must be worth checking out.

So that's my plan. With some poking and prodding from our Community Manager, Renae Bair, I’ll eventually post one or more follow-ups on what I’ve learned and my general thoughts on the experience.

Categories
Author

If you've upgraded to the recently released jQuery 1.5 you may have heard about the fancy new AJAX facilities that allow you to define things like this:

var jax = $.ajax({   url: '/some/url' })  jax.success(function() {   alert("It worked!");") });

Well, that new power is known as Deferreds and it can be useful in more places than straight-up AJAX callbacks. If you want an in-depth look at the Deferred API you can look at the jQuery Documentation or read this very in-depth look at the API. But we're here today to take a look at a few practical examples that will let you really get the most out of the new functionality.

A More Expressive setTimeout

I've always hated the Javascript API for setTimeout. In my opinion it just doesn't make sense to have the duration come after the function. Using Deferreds, we can write a very English-friendly syntax for timeouts.

$.wait = function(time) {   return $.Deferred(function(dfd) {     setTimeout(dfd.resolve, time);   }); }

Now, thanks to the Deferreds, I can write timeouts in my app like this:

$.wait(5000).then(function() {   alert("Hello from the future!"); });

This is just a small example, but it shows you how easy it is to write deferred functionality into your applications. For our next trick, let's get a little more complex.

Pretty Little Wrapper

A common thing I find myself doing in jQuery is writing a small wrapper for an API. I always hate how messy the callback code gets, let's see if we can clean it up a bit using Deferreds.

Twitter = {   search:function(query) {     var dfr = $.Deferred();     $.ajax({      url:"http://search.twitter.com/search.json",      data:{q:query},      dataType:'jsonp',      success:dfr.resolve     });     return dfr.promise();   } }

Now I can easily perform Twitter searches in my app like so:

Twitter.search('intridea').then(function(data) {   alert(data.results[0].text); });

The Advantages of Deferreds

Why would I want to use deferreds instead of standard callbacks? Well, for one, you can attach multiple callbacks to a deferred, giving you lots of flexibility in designing your application. Another way they're superior is by giving you built-in error handling. If you had a deferment that failed, you would be able to handle that as well:

function doSomething(arg) {   var dfr = $.Deferred();   setTimeout(function() {     dfr.reject("Sorry, something went wrong.");   });   return dfr; }  doSomething("uh oh").done(function() {   alert("Won't happen, we're erroring here!"); }).fail(function(message) {   alert(message) });

Deferreds are just a simple and powerful tool for you to use to make your code cleaner, more readable, and more functional. This is really just scratching the surface, so if you have any other fun Deferred tricks, I'd love to see them in the comments!

Update: From the comments, I see that it is appropriate to return dfd.promise() instead of the deferred object itself. The code has been updated to reflect as much.

Categories
Author

Six years after Ajax was widely popularized with the introduction of Gmail, we are still stuck with synchronous file uploading. Certain techniques have done their best to fill this niche by using Flash apps, hidden iframes and the like, but all have felt like hacks at best.

Enter jquery-binaryUpload, a jQuery plugin I wrote to allow asynchronous file uploading in Firefox 3.5+, Chrome 5+ and Safari 4+. It works in Firefox 3.5 through the use of the File object, while in Firefox 4+ and the other browsers it takes advantage of the FormData object. The plugin papers over these different implementations with a clean simple interface.

The included sample code demonstrates typical usage with a Sinatra or Rails app though the plugin itself is completely framework agnostic. Callbacks are descriptive while additional options are outlined in the documentation. Please report any problems you run into or suggestions you have. Enjoy!

The IE Question
So far as I have been able to glean from my research, asynchronous uploading in Internet Explorer, short of an ActiveX control or one of the aforementioned techniques, is not currently feasible. IE does not natively support the FormData or File objects and the IE9 dev team makes no mention of it on their site. My efforts to contact their dev team have been to no avail.

Categories
Author

I love the any? and empty? convenience methods that Rails and Ruby provide, they make conditional statements much easier to read. I also really dislike the default method of checking this behavior in jQuery:

if ($('some.element').length > 0) {   // ...do something }

Well, luckily jQuery is ridiculously easy to extend, so why not just mix that functionality in with a couple of quick shot plugin methods? Just add this javascript sometime after you include jQuery:

jQuery.fn.any = function() {   return (this.length > 0); }  jQuery.fn.none = function() {   return (this.length == 0); }

That’s all you have to do! Now we can make the same call as before, but it looks a little cleaner:

if ($('some.element').any()) {   // do something more readably... }

UPDATE: Apologies, I added in the empty bit as a last-second update to the post and forgot to check and realize that empty() is part of jQuery core. Updated the name to none instead.

Categories
Author

I just finished giving my “Hacking the Mid-End” talk at the Great Lakes Ruby Bash. It was a bit longer format, so I updated the slides a bit and added a third example to the code. The slides are embedded below and the new code is available in the GitHub Repository.

I’m still at the conference, but I wanted to post up the slides and code immediately! Enjoy.

Categories
Author
1
Subscribe to Jquery