Howardism Musings from my Awakening Dementia
My collected thoughts flamed by hubris
Home PageSend Comment

Plugins with and without jQuery

According to this blog entry, you can use a module pattern to better create a project that stays out of the global namespace, as well as exposing public functions and private data.

myProject.myModule = function () {

   //"private" variables:
   var myPrivateVar = "I can be accessed only from within myProject.myModule.";

   //"private" method:
   var myPrivateMethod = function () {
      console.log("I can be accessed only from within myProject.myModule");
   }

   return  {
      myPublicProperty: "I'm accessible as myProject.myModule.myPublicProperty.",
      myPublicMethod: function () {
         console.log("I'm accessible as myProject.myModule.myPublicMethod.");

         // Within myProject, I can access "private" vars and methods:
         console.log(myPrivateVar);
         console.log(myPrivateMethod());

         // The native scope of myPublicMethod is myProject; we can
         // access public members using "this":
         console.log(this.myPublicProperty);
      }
   };
}(); // the parens here cause the anonymous function to execute and return

Note the very last line with the closing curly brace and then the parentheses () This notation causes the anonymous function to execute immediately, returning the object containing myPublicProperty and myPublicMethod. As soon as the anonymous function returns, that returned object is addressable as myProject.myModule.

Constructor Pattern

Generalizing the above, we do:

  1. Make an object
  2. Define some variables and functions. These are private members.
  3. Augment the object with privileged methods.
  4. Return the object.

Example:

  function myPowerConstructor(x) {
     var that = otherMaker(x);      // Step 1.
     var secret = f(x);             // Step 2.
     that.priv = function () {      // Step 3.
        // secret x that
     }
     return that;                   // Step 4.
  }

Using jQuery

Tis a shame that jQuery's plugin guidelines cause a warning in JSLint

(function( $ ){
  $.fn.myPlugin = function() {

    // Do your awesome plugin stuff here

    // Note: there's no need to do $(this) because
    // "this" is already a jquery object
    // $(this) is the matching object.

    // Make sure to return `this` to maintain the chain.
    // Could also return a jQuery function as well.
      };
})( jQuery );

We can then write something like:

$('#element').myPlugin();
Tell others about this article:
Click here to submit this page to Stumble It