Organizing jQuery code with Flight.js


If you use jQuery for your projects and don’t organize code in some way, you should definitely check out Flight.js, a web framework created and used by Twitter. Flight.js lets you organize jQuery code in components (basically a self contained HTML markup where standard DOM events are handled by user-defined callbacks). These components communicate with each other only via events, because they cannot be referred by reference. Flight’s learning curve is minimal since it’s built on top of jQuery and API it provides is not extensive. But they can be extended by reusable objects called mixins which is a great framework’s feature.

The core use of a Flight.js looks like this:

NewCommentForm = flight.component(function() {
    this.submit = function(evt) {
        // on submit event handler
        // validate comment or something ...
        this.trigger(document, 'comment.new', comment)
    }
    this.after('initialize', function() {
        this.on('submit', this.submit)
    }
})

NewCommentForm.attachTo('form#comment-form')

In this example we create component using flight.component function. Inside we first define all event handlers. We bind them after component has been initialized. Lastly we attach the component to element(s) with selector. In example’s event handler I also triggered a custom event which by design will be intercepted by another component called Comment. That one will create the comment and add it to existing comments. Methods trigger, on and attachTo all use jQuery under the hood.

Flight.js does not make assumptions on how component’s data is handled. So if you need to deal with data than I recommend Redux and for rendering the data a template engine like Mustache (just try to make number of DOM operations as small as possible).

Flight.js can be installed with bower (and used with require.js), NPM (npm install flightjs) or by using a minified copy. I’m using NPM version since I’m using NPM for developing frontend JavaScript applications (both NPM and minified version are just bundled version of that in bower).