Tuesday, March 4, 2014

Build Your Own Javascript Library


fragment:

Build Your First JavaScript Library

Ever marvelled at the magic of Mootools? Ever wondered how Dojo does it? Ever been curious about jQuery's gymnastics? In this tutorial, we’re going to sneak behind the scenes and try our hand at building a super-simple version of your favorite library.
We use JavaScript libraries nearly every day. When you’re just getting started, having something like jQuery is fantastic, mainly because of the DOM. First, the DOM can be rather rough to wrangle for a beginner; it’s a pretty poor excuse for an API. Secondly, it’s not even consistent across all browsers.
We’re wrapping the elements in an object because we want to be able to create methods for the object.
In this tutorial, we’re going to take a (decidedly shallow) stab at building one of these libraries from scratch. Yes, it’ll be fun, but before you get too excited, let me clarify a few points:
  • This won’t be a completely full-featured library. Oh, we’ve got a solid set of methods to write, but it’s no jQuery. We’ll do enough to give you a good feeling for the kind of problems that you’ll run into when building libraries.
  • We aren’t going for complete browser compatibility across the board here. What we’re writing today should work on Internet Explorer 8+, Firefox 5+, Opera 10+, Chrome, and Safari.
  • We aren’t going to cover every possible use of our library. For example, ourappend and prepend methods will only work if you pass them an instance of our library; they won’t work with raw DOM nodes or nodelists.
One more thing: while we won’t be writing tests for this library, I did that when first developing this. You can get the library and tests on Github.

Step 1: Creating the Library Boilerplate

We’ll start with some wrapper code, which will contain our whole library. It’s your typicalimmediately invoked function expression (IIFE).
01
02
03
04
05
06
07
08
09
10
11
12
13
window.dome = (function () {
    function Dome (els) {
         
    }
     
    var dome = {
        get: function (selector) {
         
        }  
    };
     
    return dome;
}());
As you can see, we’re calling our library Dome, because it’s primarily a DOM library. Yes, it’s lame.
We’ve got a couple of things going on here. First, we have a function; it will eventually be a constructor function for the instances of our library; those objects will wrap our selected or created elements.
Then, we have our dome object, which is our actual library object; as you can see, it’s returned at the end there. It’s got an empty get function, which we’ll use to select elements from the page. So, let’s fill that in now...........

continued: http://code.tutsplus.com/tutorials/build-your-first-javascript-library--net-26796

No comments:

Post a Comment