2

Namespacing is new to me in js - and my project has grown very complex so it's time to tame the beast :-P

I have created a namespace foo in foo.js using the module pattern.

var foo = (function () {       
        update: function () {
            alert('z');
        }
    };
}());

I can call foo.update in the document ready function on an html page with $(function () {foo.update(); });

But I can't seem to get it to fire calling from another js file.

I am trying to call it from bar.js

function updateTheFoo() {
    foo.update();
}

The actual use case is much more complicated, as I'm using it within a dynamically created jQueryUI dialog with variable buttons that are passed code on the fly - but that's the easy part...

I'm sure this is something simple - but I can't seem to find the answer.

Many thanks!

2 Answers2

1

your function should be written as follows:

var foo = (function () {       
    return {
        update: function () {
            alert('z');
        }
    };
}());

your problem as Matt says is the missing return statement. What you are using there is a module pattern which is one step further to namespacing that allows to both have a namespace and private variables/functions inside that namespace and only expose what you want with the return statement.
You can read more about the module pattern in this article on the YUI blog.

gonchuki
  • 4,064
  • 22
  • 33
  • My bad - copy paste error from my code :-P I have the return { as suggested - nonetheless the issue with calling the function from another js file persists - any thoughts? – Charles Emerson Feb 28 '11 at 02:59
  • your code should be working then, you might have a syntax error somewhere that is preventing your code from running properly. did you take a look on firebug/web inspector to check that no JS errors are being thrown? – gonchuki Feb 28 '11 at 04:29
0

you have made your function to be self running, but on the other hand, you try calling it.

this is how it should be written if you want to manually call the function:

var foo = foo || 
    {        
        update: function () { 
            alert('z'); 
        } 
    };

foo.update();

you can also write:

var foo = foo || {};
foo.update = function() { alert('z'); };
foo.update();

// or pass a variable

foo.update2 = function(text) { alert(text); };
foo.update2('z');
Rafael Herscovici
  • 16,558
  • 19
  • 65
  • 93