views:

131

answers:

3

Hello,

(function($){   

    $.a.b  = {

     title: "ABC",

     init: function (id) {
                 /* do something here */
                  return id+'a';

              }




    };

})(jQuery);

When I try to call $.a.b.init('t'); it does not work, I mean it does not return as expected. Any suggestions?

The problem is not that $.a.b.init('t') is not working. Problem is that it returns the code of the whole function instead of returning say a string.

Thank you for your time.

+7  A: 

try

$.a = [];
$.a.b  = { ... }

or even better:

$.a = {b: {
     title: "",
     init: ...
}};

When using $.a.b a is undefined, so you cannot add to it.

Kobi
also, install firebug so you can see these errors.
Ramblingwood
@Ramblingwood - invaluable tool. But even the error console can help here: Ctrl+Shift+J on Firefox.
Kobi
+1  A: 

What exactly do you want to do? If you are writting jQuery function or a plugin please check this:

http://docs.jquery.com/Plugins/Authoring

FractalizeR
+4  A: 

Since $.a is not yet defined you cannot set the b property. First you'll need to create $.a. Alternatively, use a namespacing helper:

$.namespace = function(ns) {
    var cur = $, split = ns.split('.');
    while (split[0]) {
        cur = cur[split.shift()] = {};
    }
    return cur;
};

$.namespace('a').b = { ... };

It can also be used with deeper namespaces:

$.namespace('a.b.c.d.e.f').g = 123;
$.a.b.c.d.e.f.g; // => 123
J-P
Interesting and weird. I guess if you use that a lot you can add it for all objects, not just jQuery.
Kobi