views:

124

answers:

4

Hi, I'm trying to work with different loaded JavaScript in my page, but I'm not able to let them talk.

<html>
<script type="text/javascript" src="jquery144.js"></script>
<script type="text/javascript" src="shared_functions.js"></script>
<script type="text/javascript" src="page_function_callers.js"></script>
</html>


// shared_functions.js
$(document).ready (function () {
    function sayHello (what) {
        alert (what);
    }
});

// page_function_callers.js
$(document).ready (function () {
    $("div.my_button").click (function () {
        sayHello ("Hello world!");
    });
});

I work with jQuery and I'd like to use this way because it should let me recyle many public methods. Where I'm wrong?

+1  A: 

Try defining the function sayHello outside of your call $(document).ready.

wsanville
A: 

In your code above, the sayHello() method is only defined inside the anonymous function's scope.

This code might work better for you:

// shared_functions.js
window.MyNamespace = window.MyNamespace || {};
MyNamespace.sayHello = function(what)
{
  alert(what);    
};

// page_function_callers.js
$(document).ready (function ()
{
    $("div.my_button").click (function ()
    {
      MyNamespace.sayHello('hello world');    
    });
});

Make sure you're loading your JS files in the right order tho. There are more elegant solutions out there, but this is a fairly simple and straightforward one.

One advantage to this approach would be not polluting the global namespace.

Lior Cohen
your code will work, but what's the point? why postpone the declaration until DOMReady, and then extract it from that scope, rather than declaring it outside of the DOMReady context to begin with? and are you aware that the namespace is redundant here; simply typing `window.sayHello =...` would've worked equally well...
David Hedlund
Modified the code to reflect your comments. I'd still suggest placing this code under a namespace, if possible.
Lior Cohen
+2  A: 

The function sayHello is declared inside the scpoe of the DOMReady event ( $(document).ready ). It will not be available outside of that scope. But there is no need to declare a function inside that scope. Even if sayHello uses a lot of DOM objects (which in your example it doesn't), it will not be executed until it's being called, so the only thing you need to make sure is that such a function is not called until after DOMReady.

So you can simply remove the first and the last line in shared_functions.js, i.e. $(document).ready(function() { and }); respectively, and your code will work.

David Hedlund
+2  A: 
Pointy
that's a great hint about avoiding firebug 'anonymous' there...
David Hedlund
yes, thanks for help, this is very useful
Vittorio Vittori