amXor

Blogging about our lives online.

10.28.2010

jQuery Extensions?

I've been working with jQuery a fair bit lately. Although it gives you a fair number of handy shortcuts, I think it's true value is as an educational tool on how to use JavaScript effectively.

This means diving in to the jQuery sources. This means learning what anonymous functions and closures are all about, letting it settle, and then learning what they're about again. It also means taking 98% of all the JavaScript tutorials on the internets and throwing them out. Well, maybe not throwing them out, but putting them in to context.

What I'm digging in to right now is programming in the jQuery paradigm. What this means is bolting all my own functions onto the jQuery object through an anonymous function. I can then call these functions just as I would call the jQuery functions, making for a cleaner and more reusable codebase.

The basic pattern is this:

jQuery.js

The jQuery library.

myLibrary.js

This is where I attach my functions to the $ object. The template goes like this:

(function ($) {
    var private_var = 1;
    var private_function = function() {return "Only this closure can call me, I'm special."};
    $.cool_function = function(){
      return "Hello jQuery.";
    }
}(jQuery));

doStuff.js

$().ready(function() {
    $("h4").html($.cool_function());
});

That's it in a nutshell. For more info on wrapping your brain around why this works, see this article. I wish I would have read it earlier.

You'll note i'm not handling input from jQuery selectors. I'm going to have to let that one bounce around in my brain a bit longer...

Happy coding!

No comments:

Post a Comment

Twitter

Labels

Followers

andyvanee.com

Files