Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery namespace declaration and modular approach

I have confusion on how to proceed with my project. I am developing an enterprise app in which lots of modules are to be written. Most of module will be using lots of jQuery plugins to create complex grids, draw graphs for different purposes which means modules will be appending divs, tables etc a lot to DOM.

I want to preserver namespace since this will be large app. For that I came across prototype method and self-executing anonymous function. self-executing anonymous function seems to be recommended a lot.

My questions are

  1. Are self executing functions reusable ?I mean these are immediately executed so lets say a module draws a complex grid for a given JSON file. So will I be able to use same self-executing anonymous function for 3 different JSON files just like a jQuery plugin ?
  2. when there will be lots of modules written , they will all self execute on start-up. Will it effect Ram/Processor usage? Shouldn't it be way that modules should be called when needed ? what significance will self execution do ?

My Project Scope:

Kindly help me understand this self executing thing in my project scope, which is My project Holds a main namespace say "Myapp" and and its modules like Myapp.moduleA, Myapp.moduleB.MyApp will trigger its modules on click etc. What is best way to go for me ?

Self-Executing Anonymous Func

(function( skillet, $, undefined ) {
    //Private Property
    var isHot = true;

    //Public Property
    skillet.somevar = "Bacon Strips";

    //Public Method
    skillet.draw = function() {
        //Draw a grid
    };

    //Private Method
    function _grid(  ) {
        //
        }
    }   
}( window.skillet = window.skillet || {}, jQuery ));
like image 517
django Avatar asked Nov 02 '22 09:11

django


1 Answers

You cannot reuse a self executing function, it just executes immediately and that's it.

If you need to execute it multiple times, you should just declare a function.

A possible approach is this:

var MYNAMESPACE.Object = (function(){
    // private methods
    var somemethod = function(){};

    // public methods
    return {
         somepublicmethod: function(){}
    };
})();

Now you can call it like this:

MYNAMESPACE.Object.somepublicmethod();

As for executing upon startup. Provided you only create methods and don't DO anything immediately inside your declaration, it won't affect performance too much unless you have a really big amount of modules. If that's the case, you should probably look into the asynchronous module loader pattern (AMD). RequireJS is a good example of that: http://requirejs.org

I wrote an article about JS namespaces which could be interesting for you:

http://www.kenneth-truyers.net/2013/04/27/javascript-namespaces-and-modules/

like image 151
Kenneth Avatar answered Nov 15 '22 04:11

Kenneth