开发者

problem calling namespaced function from javascript function in another js file

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'开发者_如何学Gom 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!


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.


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');
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜