Monday, July 23, 2012

2012: What Javascript Frameworks I Use and Why

Wow, it's been almost four years since my last post: clearly this whole blogging habit hasn't taken hold yet.  I'm back now though, and hopefully this is the start of a more regular routine.  Since my previous posts have all focused around Javascript library selection, I thought I'd start back up again with a breakdown of the different Javascript libraries I currently use.

Now I'll be the first to admit I'm not "bleeding-edge" with my choices, and there are likely newer and better alternatives to the libraries on this list out there.  However, the libraries on this list do what they do very well AND have solid developer support AND a healthy community behind them, which can't always be said for the library du jour.

So, without further adieu ...

jQuery

jQuery is so popular that for many on Stack Overflow it has become synonymous with "Javascript" itself.  Between 60%-70% (depending on whose counting) of the most popular sites use jQuery, and jQuery is even influencing discussions on the next version of javascript.  Even Microsoft has embraced jQuery.

Why all the love?  Essentially it's because jQuery makes Javascript better.  jQuery's event hookups, AJAX calls, DOM manipulation, etc. all offer a superior API to the native browser calls, plus jQuery handles any browser inconsistencies.  It's fairly safe to say that using jQuery will change how you program in Javascript.

Underscore

I started using Underscore because Backbone required it, but I quickly discovered that the library was a great replacement for many of the Mochikit functions that I missed.  While jQuery provides each and map, Underscore offers each, map, reduce, find, filter, reject, all, any, min, max, ... you get the idea.  Plus they are can be chained together, kinda like jQuery (only with slightly worse syntax): _(someList).chain().map(function1).reduce(function2).min().value();

Other really great stuff from Underscore includes bind/bindAll, keys/values, extend, and the various is* functions.  Underscore even has a decent templater (although it's no Handlebars), making it the true "missing features of Javascript" library in my book.


Backbone

Back when I wrote single-page Javascript I used to think that MVC libraries were overkill ... and I still think that, for simpler sites.  But if you're going to write a "thick client", ie. a completely Javascript-powered site, a MVC library is pretty much a requirement.

Backbone provides classes for models, views, and collections.  Models hold data and can trigger events when that data changes, collections hold models, and views interact with the DOM to both reflect and set the data in models.  The separation between models and views is hugely helpful when writing large applications.

Now the C in  MVC normally stands for controller, but Backbone doesn't provide a controller class ... and that's ok, because you don't need one (your controller is basically just normal JS; it doesn't need extra functionality).  What Backbone does provide however is a router class, which helps your controller handle all of the (pure-JS) "page" transitions in your app.  Using the router a user can go to "/#foo" and Backbone will know to run your "handleFooPageLoad" function.

Handlebars

This is another "not so important for the little guy" library.  If you're not messing with HTML that much, just plain old HTML files and jQuery code will work for you.  However, if you're finding that your Javascript is full of strings of HTML, and if your designer has to pester you every time he wants to add a class or change a word of verbiage, you need to start using templates.

With Handlebar's templates you can specify a template like "<a href='{{url}}'>{{linkText}}</a>", and then use a JS object like "{url:'www.example.com', linkText:'This is an example link'}" to get the HTML you actually want, ie. "<a href='www.example.com'>This is an example link</a>".  The templates can either live in script tags in your HTML files, or in their own separate files; either way they're much easier for someone else (like your company's designer) to work with.

Quick side note: Backbone's views are very agnostic about how they render themselves, which means you can generate your elements however you want ... including using Handlebars.  There are even Backbone libraries for combining the two (although I personally have never used them).

XRegExp

This is the most specialized library of them all, but it's still worthwhile for anyone who needs to do anything serious with regular expressions in Javascript.  It adds a number of "missing features" from the regular expression functionality in JS, including named groups!  Why does that matter?

Well let's say you have (as I once did) a large line of text that needed to be parsed in to some 20+ variables.  Normally you would either have to write a bunch of different regular expressions, or else write one giant expression that's difficult to work with because everything has to be referenced by index.  With named group regular expressions you can "name" each group in the expression, which makes it easy to access exactly the chunk of parsed data that you want.

Named groups are just one of the many great regular expression improvements in this library.  If you're using regular expressions a lot in your JS, I highly recommend checking this library out.

Require

I've only started using Require somewhat recently, so while I really like it I can't endorse it quite as heartily as the other libraries.  Require basically provides a new way to "load" your Javascript files.  One minor benefit is a slight speed increase, as the loader can request multiple files at once.  The real benefit though is that using the loader forces you to expose your dependencies.

Let's say you have a class Foo, and you want to change some aspect of it, only you're afraid that doing so might break some other code that uses Foo.  Or maybe someone else wrote Foo and you're just looking to understand how it relates to your other classes.  Because Require forces you to spell out your dependencies you can easily find out exactly which classes use Foo, or which classes Foo itself depends on.

It's a little hard to explain why this is so great, since it sounds just like extra meta-data.  Once you start using it though you appreciate how you can tell for certain where every variable in a file is coming from, or how you can recognize that a class has grown to depend on another class which it really has no business being involved with at all.


So that's it for my library breakdown.  Hopefully I've introduced someone out there in teh intarweb to a new library, and maybe someday I'll even take a more in depth look at what these libraries have to offer.  If I can get myself blogging more regularly that is :-)

Sunday, September 21, 2008

Initial MochiKit=>JQuery Notes/Thoughts

First off, I decided to keep "$" as a document.getElementById alias, rather than let it be jQuery's alias (which it is by default). I did this because:
A) even with jQuery around, a document.getElementById alias is still useful
B) this way I didn't have to change nearly as many lines of existing code

But since I hate unnecessary long function names, I kept jQuery aliased to "$". Anyhow, here are a few specific comparisons between the two:
  1. A Better For/Each Function:
    forEach(someArray, function(value) {
    console.log(
    value);
    });

    becomes:
    $$.each(someArray, function(index, value) {
    console.log(
    value);
    });
    If your variable's type isn't important, you can also do:
    $$.each(someArray, function() {
    console.log(this
    );
    });

    but since "this" has to be an object, using it changes the type of the value to be "object" (even if the array was of primitives).

    Basically the two libraries have the same thing, just implemented differently. I love that jQuery provides an index variable, but I hate that they make it the first argument to the callback. If they'd only made the value array the first argument (as they did with their map function), I wouldn't even have to specify the index arg in the nine out of ten times I don't need it.

    So, while jQuery wins in the 1 out of 10 times I do need an index variable, MochiKit is a bit more convenient the rest of the time.

  2. Getting an element by its ID:
    var a = $("someId");
    becomes:
    var a = $$("#someId");
    but that's not really an accurate comparison, because "a" goes from being an HTML DOM element to being a jQuery results object. To get the actual HTML element, you need to do:
    var a = $$("#someId").get(0);
    Once you're used to working in jQuery land though, you find you often would rather have a jQuery results object though, as everything in jQuery "chains" off of such objects.

  3. Event hookup:
    connect(someElement, "onclick", clickHandler);
    becomes:
    $$(someElement).click(clickHandler);
    Now this is where jQuery really started to shine for me. By making the event types the name of the connection methods, jQuery eliminates the need to have "connect". But the brevity doesn't stop there. Let's say you want to connect an element that you don't already have as an object. In MochiKit you'd have to do:
    var button = getElementsByTagAndClassName("input", "submitButton");
    connect(button, "onclick", clickHandler);
    but with jQuery, that is reduced to a single line:
    $$("input.submitButton").click(clickHandler);

I'll probably have more direct comparisons later, but even with just what I've seen so far, I'm already thinking about revising my migration plan. Essentially all I want out of MochiKit is the utility functions that jQuery doesn't have, and the createDOM aliases. To get them I was going to create a MochiKit-jQuery plug-in. However, almost all of the functions in the MochiKit Base library aren't in jQuery, so it seems sort of silly to make a plug-in for them. Instead, I think I'm just going to keep using MochiKit Base "as is", and then make a jQuery plug-in for the createDOM aliases (by the same logic I could also just include MochiKit DOM, but then I'd have to include the Iter and Style libraries as well, and that is a lot of duplication of functionality).

Sunday, September 7, 2008

JQuery vs. MochiKit

I could go off on a rant here about how MochiKit "used to be cool man, but now they're not". I won't, because I've already done that elsewhere, and it's not exactly very productive. So what I will say is this: MochiKit has a lot of clever ideas, including a few really clever ideas, that most of the other Javascript frameworks don't. But its creator and primary contributors take the "if it ain't broke, don't fix it" philosophy to the extreme, and as a result the "active development community" responsible for the framework is anything but.

Because of this, I've come to the conclusion that tying your project's fate to MochiKit is like investing all your money at the turn of the century in horse carriage manufacturing: fine if your choice only matters in the near future, but in the long term that newfangled "horseless carraige" technology will make you wish you'd invested in automobiles. As a result, I'm now in the process of migrating both my personal projects and the website of the company I work for from MochiKit to JQuery.

Now the first and most obvious problems of doing this are the "you say tomatoe, I say tomatow" issues: each framework has its own name for various functionality they share. On top of that there's the differences in approach of the two frameworks, the most significant being that while everything in MochiKit is a function, almost everything in JQuery is a method. This makes a huge difference in how, say, event handling is done. And then beyond all that there are the things that JQuery just flat out doesn't have that MochiKit does, which I have to try and liberate from MochiKit without taking half a library of dependencies with it.

So, the next few blogs will chronicle this whole transition, both my thoughts on doing it and what I learn about both frameworks while doing it. And at the end, perhaps I'll even have some sort of "the best parts of MochiKit as a JQuery plug-in" to share with the world. Who knows?

Mission Statement

Mission Statement: This blog has none. At best it has a theme, which is already implied by the title (coding). I plan to use this blog to share new tricks I learn, unique solutions I find to problems, and of course the obligatory occasional article of programmer humor (eg. code quality measurement). Hopefully someone out there in that thar intarweb thing will find it useful and/or entertaining.

By the way, for those of you who are wondering about the title, I'm neither a fanatical fan of Wu Tang Clan nor random old martial arts movies, although the title is a pun on "Ghostfaced Killer". I actually got it from Dungeons and Dragons (3.5 edition); yes I am that much of a nerd (plus the title went well with another online moniker of mine, which I won't state out of fear of reprizal from crazy internet stalkers and/or people I've flamed in newsgroups).