2

Just like C# or Java to put all my jQuery code in one .js file, something like this:

namespace MySite
{
    class HomePage
    {
        function Init(params) { /*...*/ }
        //...
    }

    class ContactForm
    {
        function Validate() { /*...*/ }
        //...
    }
}

So you can call it in this way:

$(function () {
    MySite.HomePage.Init({a : "msg"});
});

I have this code, but doesn't work:

$.namespace = function () {
    var a = arguments, o = null, i, j, d;
    for (i = 0; i < a.length; i = i + 1) {
        d = a[i].split(".");
        o = window;
        for (j = 0; j < d.length; j = j + 1) {
            o[d[j]] = o[d[j]] || {};
            o = o[d[j]];
        }
    }
    return o;
};

$.namespace('$.mysite');

$.mysite.Home = function () {

    function Home(params) {
        //...
    };

    Home.prototype = function () {
        Init: function () {
            alert("lol");
        }
    }
}; 

Is it possible to that in jQuery? (something similar or recommendations / examples to keep my jquery code organized. ) Thanks for your time and answers (sorry for my bad english).

4 Answers 4

3

Why not just put it inside a js object?

var _o = {};
_o.module1 = {};
_o.module2 = {};

_o.module1.someFunc = function(){//code};
_o.module2.someFunc = function(){//code};
Sign up to request clarification or add additional context in comments.

Comments

3
var MODULE = (function () {
     var my = {},
     privateVariable = 1;

     function privateMethod() {
     // ...     
     }
     my.moduleProperty = 1;
     my.moduleMethod = function () {
     // ...     
     };
     return my;
     }());

If I understood well, you want to add your namespace under jQuery. To do that you need to use technique called sub moduling;

MODULE.sub = (function () {
     var my = {};
     // ...
     return my;
 }());

Or, you can use module import:

(function(jQuery){
    jQuery.myNamespace = {};
    jQuery.myNamespace.myFunc = function(arg){
        console.log(arg);
    };
}($));

After that you can run it like this:

$.myNamespace.myFunc("somevalue")

And it will write:

LOG: raera

For more techniques and examples, see http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth

Comments

0
var nameSpace= {};
nameSpace.nameSpace1= nameSpace.nameSpace1|| (function()
   {
   }());

Comments

0
MySite = {
    HomePage : {
        Init: function(params) { /*...*/ }
    },
    ContactForm: {
        Validate: function() { /*...*/ }
    }
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.