Calling function from a variable - javascript

I want to call a function and the function name is stored into a variable, but it is giving error. I am trying to call a function uploadDocumentCallback but its name is stored into a variable
$scope.uploadDocumentCallback(data,status,headers,config); //its working fine if i'm passing callback function name directly.
$scope.callback = "uploadDocumentCallback"; //this is my variable where I store function name
var callbackFunction = $scope.callback;
$scope.callbackFunction(data,status,headers,config); //not working
callbackFunction(data,status,headers,config); //not working
$scope.callback(data,status,headers,config); //not working
Please suggest me that how can I achieve this?

I managed it to work
$scope[$scope.callback](data,status,headers,config);

Related

How to save value from JQuery $.post to a Javascript Global Variable

I am using Javascript and JQuery.
I have the following Variable var RoleID=""; and I have placed it outside of all functions.
I have a function
role_submit(){
var role=$('#emp_role').val();
var url="submitrole.php";
$.post(url, {role2: role} ,function(data){
var RoleID=data;
alert(RoleID);
})
}
This function gets the value of an <input type="text" id="emp_role"> and submits to a url='submitrole.php' using JQuery $.post and gets back an ID from url='submitrole.php' in return which is saved in RoleID and afterwards RoleID is alerted. This all is executed using <button onclick="role_submit();" type="submit">Submit</button> and works fine meaning that the ID which should come from url='submitrole.php' comes accurately and is also alerted accurately.
The issue arises when I use following function to look at the global variable var RoleID
function alert_roleID(){alert(RoleID);}
I call to this function using
<button onclick="alert_roleID();" type="submit" >Role ID</button>
This time the alert pops up showing nothing rather than the ID I got back from url='submitrole.php'. How can I get the global variable RoleID to have the value of from url='submitrole.php'?
There are two ways.
Set the variable to the window explicitly. Window is the global scope.
function role_submit(){
var role=$('#emp_role').val();
var url="submitrole.php";
$.post(url, {role2: role} ,function(data){
window.RoleID=data;
alert(RoleID);
})
}
Or define the variable in the global scope. If you do it this way, make sure you don't use var when you redefine it. If you use var it makes a new variable only visible in that scope (function).
var RoleID;
function role_submit(){
var role=$('#emp_role').val();
var url="submitrole.php";
$.post(url, {role2: role} ,function(data){
RoleID=data;
alert(RoleID);
})
}
Once you declared the variable outside, you should not use 'var' once again inside the function since this will recreate the local scoped variable instead of a global scoped variable and inaccessible outside the function. So you can remove the 'var' as below,
var RoleID = '';
role_submit(){
var role=$('#emp_role').val();
var url="submitrole.php";
$.post(url, {role2: role} ,function(data){
RoleID=data;
alert(RoleID);
})
}

Passing a local variable to a function that I can only make limited changes to

I am just starting to get into JavaScript and couldn't find an exact scenario like this yet on SO, so I'm going to try my luck. I have two functions in an external JS file which create video feeds on our website:
function getVideos() {
//gets a list of videos
}
//callback function automatically called by getVideos()
function response(jsonData) { //can't change this line
var resp = document.getElementById("resp"); //can change this line and any subsequent lines
//parses data and populates resp
}
Then, from the HTML side, we just call getVideos() and the video feed will be created and populated.
However, I want to be able to pass any element ID I want into response() so that we can create multiple video feeds in different places on the same page. The thing is I can't change the function declaration of response() to include another parameter. Or at least I'm not led to believe I can by the company hosting our videos.
I've tried wrapping response() with getVideos() and passing an element ID from there, but then response() doesn't get called, and the only solution I can think of is resorting to storing an element ID in a global variable, which I know is a no-no in general in JavaScript.
My question is: Do I just bite the bullet and use a global variable, or is there another way?
For more info, here is our JS code as it stands now (with the closure): http://www.thebearrocks.com/Other/js/videoFeed/createVideoFeed.js
And here is the tutorial on response() we're following from the host of our videos: http://support.brightcove.com/en/video-cloud/docs/making-media-api-calls-dynamic-script-tags
may be you can use arguments? like so:
function response(jsonData) { //callback function automatically called by getVideos()
var elemId = arguments.length<2 ? "resp" : arguments[1]+"";
var resp = document.getElementById(elemId);
//parses data and populates resp
}
or, declare second argument what has default value like this:
function response(jsonData, elemId) {
elemId = elemId || "resp";
var resp = document.getElementById(elemId);
//parses data and populates resp
}
in this case function can be called as with one or two arguments
I've tried wrapping response() with getVideos() and passing an element ID from there, but then response() doesn't get called, and the only solution I can think of is resorting to storing an element ID in a global variable, which I know is a no-no in general in JavaScript.
My question is: Do I just bite the bullet and use a global variable, or is there another way?
No. Not the id variable needs to become global, but your local response function needs to for getting called back from the JSONP script - you're going to create a closure.
You can "export" it by calling
window.response = mylocalResponseFunction; // you did name that local var "response"

Can't access a global variable

I'm trying to access a global variable in testGlob1, however I'm not able to do so:
var displayVar;
function globVariable(){
displayVar="2";
}
function testGlob1(){
alert(displayVar);
}
You aren't showing how your variable is being assigned a value. Is globVariable() being called on load of the document? Im sure this would work:
var displayVar=2;
function testGlob1(){
alert(displayVar);
}

jquery pass value into function AFTER function?

I am new to javascript & jQuery. I'm trying to create a feature for my site that let's people display badges they have earned on their own site (and I would supply a bit of code they could just copy/paste). I had someone help me with the javascript and I have it working perfectly, but I can't find any jQuery documents that explains it to me?
<script type="text/javascript">
(function(id) {
// include js via php file with the id in as a parameter
})("myid");
</script>
The id is passed in the area labeled "myid", in jQuery can you pass in a static variable this way? When I try to delete ("myid") and change it to var id = 'myid', the function no longer works.
The occurrence of "myid" in the code you are showing is not a static variable. It is a string literal that is being passed as an argument to an anonymous function. The anonymous function is declared and then is immediately getting called.
If you are wondering why the programmer wrote the JavaScript the way they did. The following might help.
Both of the examples below will display "myid" in an alert:
Example 1:
<script type="text/javascript">
var id = 'myid';
alert(id);
</script>
Example 2:
<script type="text/javascript">
(function(id) {
alert(id);
})('myid');
</script>
The first example declares "id" as a variable. It is a global variable and is actually added as a property to the window object. The second example defines an anonymous function and immediately calls it, passing in 'myid' as the value of the "id" parameter. This technique avoids using a global variable.
Of course, you could also avoid the global variable by doing the following:
<script type="text/javascript">
(function() {
var id = 'myid';
alert(id);
})();
</script>
If you stick "myid" in a variable and then pass in that variable, it'll work. Like this:
var memberID = "myid";
(function(id) {
// include js via php file with the id in as a parameter
})(memberID);
If you say this...
(function(id) {
// include js via php file with the id in as a parameter
})(var id = 'myid');
...you're attempting to stick a variable declaration in a function call, which won't work. That's why declaring the variable above and apart from the function call won't throw any errors.

How do I pass the name of a function as a parameter then reference that function later?

I want to pass the name of a function "testMath" as a string into a wrapper function called "runTest" as a parameter. Then inside 'runTest' I would call the function that was passed. The reason I'm doing this is because we have a set of generic data that will populate into variables regardless of the test, then a specific test can be called, based on whatever the user wants to test. I am trying to do this using javascript/jquery. In reality the function is much more complex including some ajax calls, but this scenario highlights the basic challenge.
//This is the wrapper that will trigger all the tests to be ran
function performMytests(){
runTest("testMath"); //This is the area that I'm not sure is possible
runTest("someOtherTestFunction");
runTest("someOtherTestFunctionA");
runTest("someOtherTestFunctionB");
}
//This is the reusable function that will load generic data and call the function
function runTest(myFunction){
var testQuery = "ABC";
var testResult = "EFG";
myFunction(testQuery, testResult); //This is the area that I'm not sure is possible
}
//each project will have unique tests that they can configure using the standardized data
function testMath(strTestA, strTestB){
//perform some test
}
Do you need the function names as string? If not, you can just pass the function like this:
runTheTest(yourFunction);
function runTheTest(f)
{
f();
}
Otherwise, you can call
window[f]();
This works, because everything in the 'global' scope is actually part of the window object.
Inside runTests, use something like this:
window[functionName]();
Make sure testMath in the global scope, though.
I preffer to use apply/call approach when passing params:
...
myFunction.call(this, testQuery, testResult);
...
More info here.

Categories