Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

call a javascript method in another .js file

what is the rule around calling functions from one js to another ? I thought that this worked but i am not running into issue (figured it out through firefox) that a function in another js file doesn't seem to be recognized in my first js file.

Is there some rule around ordering or some trick you have to do to get this to work?

like image 236
leora Avatar asked Apr 26 '11 04:04

leora


2 Answers

It has to be accessible in the global scope somewhere. For example:

// file1.js
function hello() {
    alert("Hello, world!");
}
// file2.js
$(function() {
    hello();
});

Likely, you have something like this:

// file1.js
$(function() {
    function hello() {
        alert("Hello, world!");
    }
    // ...
});
// file2.js
$(function() {
    hello();
});

hello is only in scope of the closure defined in file1.js. Therefore, to access it in file2.js, you'd have to export it to somewhere where file2.js can get at it:

// file1.js
$(function() {
    function hello() {
        alert("Hello, world!");
    }
    window.hello=hello;
});
// file2.js
$(function() {
    hello();
});

Also, the script where the function is defined must be loaded, parsed, and executed before the function can be called from another script.

like image 136
icktoofay Avatar answered Oct 21 '22 16:10

icktoofay


Are you calling the function in an event handler, or immediately when the javascript file is loaded? If it's not in an event handler, then load order is important. If you have circular dependencies, you may need to delay some of the initialization with a "DOM ready" or window.onLoad listener.

like image 28
Austin Taylor Avatar answered Oct 21 '22 14:10

Austin Taylor