Reputation: 1989
Question:-
How can I call a function defined under a different script in the same javascript file from another function in a different script ?
Explanation:-
So I have 2 scripts in the same javascript file (default.aspx)
I have one script that does a jquery...
$.Ajax { .... OnScucess: Onsuccess () function}
Onsuccess() { call another function called date_label() }
This date_label()
function is defined in a separate script... where there is a function called
timeLine(){ within it is the function date_label() {....} }
Now when I try to call date_label in my Onsuccess()
function I get an obvious error message - undefined. But I believe there must be someway to make it work. Any ideas?
I was looking at this:-
http://answers.unity3d.com/questions/11206/call-a-function-in-a-different-script-using-javasc.html
but I dont have names for my script tags...
Upvotes: 0
Views: 67
Reputation: 91716
There's a few ways to fix this, and all of them involve controlling the scope of date_label()
. The easiest fix (which will get me yelled at shortly) is to make date_label()
global. In the file, you'd simply have:
function date_label()
{
// Implementation
}
Make sure this function is not nested within another scope, such as another function. As long as this script file has been loaded before date_label
is called, you'll be fine. What physical .js
file the functions are located in is completely irrelevant.
However, usually you don't want to pollute the global scope. For this reason, you might want to put this function within a namespace, which is usually just an object literal:
var MyUtils =
{
date_label: function ()
{
// Implementation
}
};
You would then be able to call this function anywhere like so:
MyUtils.date_label();
It's often common practice to define a namespace for your app or your library, as not to conflict with other code that might be on the page as well.
Upvotes: 1