Greg Franko

Web Development is Fun. Let's Talk About It.

Registering the jQueryUI Widget Factory as an AMD Module

AMD (Asynchronous Module Definition) script loaders are fast becoming one of the most popular and important tools for organizing and maintaining JavaScript applications. Many front-end developers, like myself, are becoming educated on the benefits of using a module system that promotes code reusability/decoupling, freeing the global namespace, dependency script management, and more.

Unfortunately, AMD script loaders, such as Require.js, are not drop-in solutions. To use an AMD module system, you must make sure every other JavaScript library used in your application is AMD Compatible.

AMD Compatible

For a JavaScript file to be AMD Compatible, the JavaScript content must be wrapped in a define() method and all module (file) dependencies must be listed.

A possible solution is to change the source of each JavaScript file you are using and make sure the content is wrapped inside of a define() method. This is both time-intensive and error-prone, since you will even have to change the source of third-party libraries that your application is using, such as jQuery.

At this point you may be scratching your head and asking yourself a few questions…

I Love My IIFE

An IIFE, or Immediately Invoked Function Expression, is a common JavaScript design pattern used by most popular libraries (jQuery, Backbone.js, Modernizr, etc) to place all library code inside of a local scope. In the words of James Padolsey, an IIFE protects a module’s scope from the environment in which it is placed. There are more benefits to using IIFE’s than just local scoping, but before we talk about some of the other benefits, let’s take a look at some code to see how to create a basic IIFE:

1
2
3
(function(){
  // my special code
}());

The above IFFE is just an anonymous function (no name attached to it) that is wrapped inside of a set of parentheses and called (invoked) immediately. Let’s break this down step by step.

The Anonymous Function:

1
2
3
4
// Anonymous function
function(){
  // my special code
}(); // The parentheses make sure the anonymous function gets called immediately

A function, without a name, is created and then called (invoked) immediately via the () at the very end.

The Parentheses

You might be wondering why we need to wrap the immediately invoked anonymous function inside of parentheses. Before I explain why, try the above code inside of a console window. Get a syntax error?

By wrapping the anonymous function inside of parentheses, the JavaScript parser knows to treat the anonymous function as a function expression instead of a function declaration, since JavaScript does not allow statements inside of parentheses. A function expression can be called (invoked) immediately by using a set of parentheses, but a function declaration cannot be.

Backbone.validateAll Plugin






Backbone.validateAll is a small Backbone.js plugin that provides an option to only validate Model properties that are currently being set or saved.

Background

Backbone.validateAll originated from a failed Backbone.js pull request. The original pull request was created because of frustration with using the Backbone.js Model validate method when validating HTML forms.

Backbone.js v0.9.1 Changes

Since Backbone.js v0.9.1 and greater, Backbone Model validation was not made to elegantly handle form validation, since the default validate method will validate all Model attributes, regardless of what particular attribute is being set or saved. For certain use cases, it is necessary to only validate a certain Model property (or form field) without worrying about the validation of any other Model property (or form field).

Performance!

Backbone core contributor, @braddunbar, presented a possible solution for this use case in the above mentioned pull request, but it still involved calling all of the validation methods within the validate() method, which can negatively affect performance.

Here is a jsPerf Test showing the performance benefits when setting Backbone Model attributes with and without Backbone.validateAll.

Documenting Your Open Source Projects







What? I Actually Have to Show People How to Use My Project?

Popular Open Source (OS) projects are self promoted by their easy to read, organized, and exhaustive documentation. Great examples include Backbone.js, Underscore.js, Lodash, Can.js, jQuery++, Underscore.js, jQuery, HTML5 Boilerplate, Require.js, Twitter Bootstrap, and many more.

These projects realize that users expect their documentation to follow a common format that includes a table of contents that houses, at the very least, a Getting Started guide, a Demos/Examples section, and a forum section to ask questions. Additional sections (ie. annotated source code, Contributor Guide) targeting potential core project contributors may also be included.

All OS developers should take note of these documentation practices and follow them when promoting their own projects. When patrolling Github to find new and interesting projects, I often find myself dismissing a project right away if there is a lack of documentation.

The project could have the most readable, brilliant, and performant code known to man, yet I (and many other developers) would never know.

But Documentation Takes Too Long to Write!

It’s true, documenting your project may take longer than writing the project code itself. But there are open source tools that can help expediate the process…

Creating Custom Project Builds With DownloadBuilder.js







Please, Just Give Me What I Want

Many of the most popular Open Source (OS) projects understand that flexibility and performance is very important for users. Since it is nearly impossible to create a project that is a perfect fit for all users, many OS projects provide a custom build option. This allows users to specify which parts of a project he/she wants and then download only those parts (thus minimizing file size).

Examples of popular OS projects that are providing custom build options now include jQuery (recent addition in version 1.8), jQueryUI, Modernizr, Lodash, Twitter Bootstrap, Can.js, etc.

After reviewing the custom build processes of the above OS projects, it seemed that each project had developed its own custom back-end build process from scratch. This architecture seemed to work well for projects with many contributors/organizational backing, but I wanted an easy solution that I could use for my own OS projects where I was the only main contributor. Since I could not find any existing OS projects that fit the bill, I created DownloadBuilder.js.

DownloadBuilder.js

Description

DownloadBuilder.js is a JavaScript library that uses the HTML5 Filesystem API to create concatenated single file custom builds for front-end projects. Since the project uses the HTML5 Filesystem API, all of its features only currently work in Chrome 21+, although it can still be used in all other modern browsers(Firefox, IE8+) to create a generated concatenated project file.

Backbone.js: Convincing the Boss Guide






Year of the JavaScript MV* Frameworks

I am officially pronouncing 2012 as the year of the JavaScript MV* frameworks. Although many people complain that the JavaScript MV* frameworks boom has created too many frameworks to choose from, which further divides the developer community, let’s look at the glass half full. The influx of JavaScript MV* frameworks has created new design patterns that have promoted JavaScript as a language that you should care about. JavaScript codebase consistency, maintainability, and performance have never been scrutinized more. This intensified focus is helping the web become an even better place to spend your time.

Although 2012 has been a big win for the JavaScript community, there is still much work to be done. Much of that work consists of educating developers, who may not be JavaScript wizards (seriously not everyone can be Paul Irish, Addy Osmani, John-David Dalton, Jeremy Ashkenas etc), that organizing their front-end codebases deserves their full time and attention.

A common argument against using JavaScript MV* frameworks by non-JavaScript wizards is that most “apps” are not complex enough to warrent using these “bloated MV Whatever frameworks” (their words not mine). Before you start screaming at your computer, let’s look at this argument in more detail using Backbone.js, one of the most popular JavaScript MV* frameworks, and custom Backbone.js builds.

Require.js 2.0 Shim Configuration







Require.js 2.0 was recently released by James Burke, and with it comes a bunch of bug fixes and enhancements. The major enhancement that I wanted to shed light on includes the new Shim configuration.

The Shim configuration is a much needed upgrade to the Require.js core that allows Require.js to load non-AMD compatible scripts. In my previous post Using Backbone.js with Require.js, I covered how Use.js, a Require.js plugin created by Backbone.js core contributor Tim Branyen, was necessary to load Backbone.js and Underscore.js (both AMD incompatible) with Require.js. This was a good solution for integrating these two wonderful projects together, but it was still another project dependency that you needed to keep track of.

Using Backbone.js With Require.js






Backbone.js is a great client-side MV* (not MVC) JavaScript framework that provides structure to JavaScript applications by providing View, Model, Collection, and Router classes. Backbone also provides a pub sub (publish subscribe) mechanism, by allowing each of it’s objects to trigger and bind to events.

Backbone Views act as a combination of traditional MVC Views and Controllers, since they allow you to organize all of your JavaScript event handlers while also providing a mechanism for adding dynamic HTML to your page through the optional use of JavaScript templates. Views will also often be where you set data on your Models.

Here is an example Backbone View class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
   var View = Backbone.View.extend({

        // Represents the actual DOM element that corresponds to your View (There is a one to one relationship between View Objects and DOM elements)
        el: 'body',

        // Constructor
        initialize: function() {

            //Setting the view's model property.  This assumes you have created a model class and stored it in the Model variable
            this.model = new Model();

        },

        // Event Handlers
        events: {

            "click #example": "promptUser"

        },

        render: function() {

            // Updates the text of the element with an ID attribute of example            
            this.$el.find("#example").text("This is an example");

        },

        promptUser: function() {

            prompt("Isn't this great?", "Yes, yes it is");

        }

    });

Creating a jQuery Plugin Using jqBoilerplate

What is a jQuery Plugin?

A typical jQuery plugin is a method that is added to the jQuery prototype object, fn, that interacts with one or more DOM elements wrapped in a jQuery object. Something like this:

1
2
3
4
5
6
//Adding the tooltip method to the jQuery prototype
$.fn.tooltip = function ( options ) {
    return this.each(function () {
        //Plugin logic
    });
}

Then the jQuery plugin can be used like this:

1
2
//Calls the jQuery tooltip plugin on a DOM element
$("input#firstName").tooltip();