Archive for July, 2011

JavaScript: implementing a javascript component (bestpractice)

Sunday, July 31st, 2011

Here is a best practice to implement a javascript component. (code skeleton)

// do this one per file
var myModule = myModule || {}


// Do an "scoping function" once per Component
(function($){

  // some privates members here

  // --------- myModule.MyComponent Constructor --------- //
  myModule.MyComponent = function MyComponent(arg1,argN){

    // little trick allowing to instanciate any of the two following ways:`
    //   1) var comp = new myModule.MyComponent(..)
    //   2) var comp = myModule.MyComponent(..)
    if (!(this instanceof MyComponent)) {
    	return new MyComponent(arg1,argN);
    }
  }
  // --------- /myModule.MyComponent Constructor --------- //

  // --------- Public Methods --------- //
  myModule.MyComponent.prototype.publicMethodA = function(){
     // some stuff
  }
  // --------- /Public Methods --------- //


  //private methods here
  function privateMethodB(){

  }
})(jQuery);