boldr by Nicolas Mérouze

jQuery Underscore together

I like jQuery, but sometimes I miss utility functions from Prototype.js. But with Underscore, this is over! You can use invoke, first, last, compact... and it's only 2kb packed and gzipped.

Example

I find it very useful when I get JSON with jQuery. Let's take a Twitter example:

$.getJSON("http://search.twitter.com/search.json?&q=from:nmerouze&callback=?", function(data) {
});

To get the results with jQuery you will be very limited: $.each, $.map and that's pretty much all. With Underscore it's easy to build an array of tweets from the results:

$.getJSON("http://search.twitter.com/search.json?q=from:nmerouze&callback=?", function(data) {
  var tweets = _.pluck(data.results, "text");
});

In addition, if you're a Ruby developer you're addicted to first and last on arrays:

$.getJSON("http://search.twitter.com/search.json?q=from:nmerouze&callback=?", function(data) {
  var tweets = _.pluck(data.results, "text");
  alert(_.first(tweets)); // or alert(_.last(tweets));
});

And you have an OOP style too:

$.getJSON("http://search.twitter.com/search.json?q=from:nmerouze&callback=?", function(data) {
  var tweets = _(data.results).pluck("text");
  alert(_(tweets).first()); // or alert(_(tweets).last());
});

There's a lot of functions (not just for arrays), so take a look at the documentation which is great!

A final library

Now I have my utility functions, I want to use classes. I found a little Javascript lib from June to do that in a way I like. It's very small and there's just what I need: modules, classes, methods and mixins.

module("Boldr", function(c) { with(c) {
  module("Hello", function() {
    def("hello", function() {
      alert("hello " + this.name);
    });
  });

  constructor("MyClass", function() {
    include(Boldr.Hello);

    def("initialize", function(name) {
      this.name = name;
    });
  });
}});

var myClass = new Boldr.MyClass("world");
myClass.hello();

I'm in a more familiar world here. There's JS.Class to do that too but I don't need all the core functions.

Conclusion

Now I have a fast and small way to write my Javascript and it's perfect (for now anyway).

If you liked the article and/or want to talk to me about it, you can follow me on twitter.