views:

225

answers:

1

I'm looking for a barebones javascript example that demonstrates how the javascript plugin architecture works with large javascript libraries (such as raphael or jquery). In either scenario, you build plugins by ensuring your custom plugin follows this pattern: jQuery.fn.pluginName -- so assume I have a library:

myLibrary = (function() {
    //my fancy javascript code
    return function() {
        //my return object
    };
});

How would fn be incorporated into the above myLibrary object to ensure that he resulting plugin is callable? I instantiate myLibrary like so:

var lib = new myLibrary();

And now I have included a reference to my plugin in my page:

myLibrary.fn.simplePlugin = function() { //more fancy code }

So finally, I can just call:

lib.simplePlugin();

Basically, what magic is actually occuring when the .fn is used during the creation of the plugin?

+2  A: 

The fn object in jQuery is simply an alias for the prototype property of the jQuery constructor, here is a really basic structure how about it works:

(function() {
  var myLibrary = function(arg) {
    // ensure to use the `new` operator
    if (!(this instanceof myLibrary))
      return new myLibrary(arg);
    // store an argument for this example
    this.myArg = arg;
    //..
  };

  // create `fn` alias and define some "core" methods
  myLibrary.fn = myLibrary.prototype = {
    init: function () {/*...*/}
    //...
  };
  // expose the library
  window.myLibrary = myLibrary;
})();

Then since myLibrary is a constructor function, you can extend its prototype (or fn in this example is the same object):

// a "plugin"
myLibrary.fn.myPlugin = function () {
  alert(this.myArg);
  return this; // return `this` for chainability
};

myLibrary("foo").myPlugin(); // alerts "foo"

I really recommend you to read about constructor functions, here are some good resources:

CMS
Thank you -- wonderful answer.
TimDog