i have a load(callback) function which takes a callback function as parameter. Can this callback function access variables present in its parent function i.e. load()
(function load(callback)
{
return $.get("../somepage.aspx", {data:data}, function (response, status, xhr){
var x = 10;
if(typeof callback === 'function') { callback(); }
}
})(done);
var done = function(){
//do something with x here
alert(x);
}
You cannot access x like you want because it is outside the scope of the done function.
You need to pass x to the callback:
(function load(callback)
{
return $.get("../somepage.aspx", {data:data}, function (response, status, xhr){
var x = 10;
if(typeof callback === 'function') { callback(x); }
}
})(done);
var done = function(x){
//do something with x here
alert(x);
}
I suspect this is what you want but to but I am taking a stab in the dark here seeing as how the code in the question has serious syntax problems (i.e. done is not a child of parent.)
Nope, it can't because the callback's scope is totally outside the calling scope. Pass x as a parameter in the callback.
Related
How to pass the variable from outside to onResourceRequested function?
I am not able to access the variable testvar inside the callback function of onResourceRequested property.
Any idea how to fix this issue?
Below is the sample code I used for testing
var phantom = require("phantom");
var _ph, _page, _outObj;
phantom.create().then(function(ph){
_ph = ph;
return _ph.createPage();
}).then(function(page){
_page = page;
var testvar = "WHY THIS IS NOT PRINTING";
_page.property('onResourceRequested', function (req, networkRequest) {
console.log("THIS LINE WORKS");
console.log(testvar); // THIS DOESNT WORK
});
_page.property('onResourceReceived', function (res) {
//console.log('received: ' + JSON.stringify(res, undefined, 4));
});
return _page.open('https://www.ammaus.com/', function (status) {
if (status !== 'success') {
console.log('FAIL to load the address');
}
_ph.exit();
});
}).then(function(status){
console.log(status);
return _page.property('content')
}).then(function(content){
_page.close();
_ph.exit();
}).catch(function(e){
console.log(e);
});
Use arrow function (ES6) like this:
_page.property('onResourceRequested', (req, networkRequest) => {
console.log("THIS LINE WORKS");
console.log(testvar); // THIS DOESNT WORK
});
An arrow function does not newly define its own this when it's being executed in the global context; instead, the this value of the enclosing execution context is used, equivalent to treating this as closure value.
I have a (asynchronous) function that gets the ID of a logged in user in Chrome. I'm trying to return the value of the ID with a callback but it keeps returning 'undefined'.
Before someone tries to mark this a duplicate, I used the code from here (and tried other places too): How to return value from an asynchronous callback function? But it didn't work:
function getGaia(callback) {
chrome.identity.getProfileUserInfo(function(userInfo){
var userId = userInfo.id;
callback(userInfo.id);
});
}
getGaia(function(id){
return id;
});
var gaiaId = getGaia();
I get the following error:
'callback' is a not a function
What exactly am I doing wrong / what is the correct code?
That is because you are not providing a callback.
function doSomethingLater(callback) {
setTimeout(callback, 1000);
}
console.log('This is before the callback');
doSomethingLater(function() {
console.log('This is the callback')
});
So when you are calling var gaiaId = getGaia(); you are not passing in a callback function
[Edit] This is what your code would need to look like:
function getGaia(callback) {
chrome.identity.getProfileUserInfo(function(userInfo){
var userId = userInfo.id;
// This will call the function that you pass in below
//and pass in userInfo.if as a parameter
callback(userInfo.id);
});
}
var gaiaId = getGaia(function (id) {
// id === userInfo.id from above
// Do something with the id that you pass in
});
You can think of functions like variables in JavaScript,
So you can assign a function to a variable like this:
var foo = function () { ... }
This means that you can pass this into functions like normal variables. When you pass the function in as a parameter, you are assigning the function to the name that you specify in the parameters:
var foo = function () { ... }
function hasCallback(callback) {
// The following two line do exactly the same thing:
callback(); // Using the function that you passed in
foo(); // Using the function directly
}
hasCallback(foo);
All I have done above is, instead of creating the variable foo I just created the function inline:
var foo = function () { ... }
function hasCallback(callback) {
// The following two line do exactly the same thing:
callback(); // Using the function that you passed in
foo(); // Using the function directly
}
hasCallback(foo);
// Becomes:
function hasCallback(callback) {
callback(); // Using the function that you passed in
}
hasCallback(function () { ... });
Can function be executed after some variable got value (or changed) in JavaScript?
In my example, the variable is hoisted at first which is declared to be a global, then will assign some value to it in getData() function.
I have tried using .delay() method, but i don't know how much time the ajax needs.
briefly describe:
1) Declaring variable
2) calling getData() function, then assign the data to variable
3) calling funcA() function
4) calling funcB() function and pass function doSomething() as a callback in funcA()
5) calling the callback function in funcB()
6) log the data in doSomething()
<script>
var variable;
variable = getData();
funcA();
function funcA() {
funcB(doSomething);
function doSomething(data) {
console.log(data);
}
}
function funcB(callback) {
if (variable !== undefined) {//it is obviously undefined.
callback(variable);
}
}
</script>
//another js file
<script>
function getData() {
//get data by using ajax
//i don't know how much time it needs.
return data;
}
</script>
change your getdata to this:
function getData() {
$.ajax({
url: "some url",
success: function(result){
variable = result;
//do everything that should be done here or call your callback
});
}
Is it possible to pass a callback function that does not exist yet? My goal is to have a common function that will wait for another callback function to exist, when it does exist, it should execute it. This is what I have so far, but I can't figure out how to pass the function in that doesn't exist as a function yet.
function RunTemplateFunction(callback, userInfo) {
if ($.isFunction(callback)) {
callback(userInfo);
} else {
var myInterval = setInterval(function () {
if ($.isFunction(callback)) {
clearInterval(myInterval);
callback(userInfo);
}
}, 200);
}
}
I run the function like this:
RunTemplateFunction(MyFunctionToRun, GetUserInfo());
I get MyFunctionToRun is undefined for obvious reasons, I also tried the workaround of passing the function as a string and then convert the string to a function using eval(). But that throws the same error. I also thought of using the new function(), but that actually creates a new function.
Any help is appreciated. thank you.
If you call RunTemplateFunction by undefined there is no way we can see, is callback is defined or not, as we don't have reference to anything.
If you can modify the declaration to accept object as below, we can achieve what we want
function RunTemplateFunction(options, userInfo) {
if ($.isFunction(options.callback)) {
console.log('called1',userInfo);
options.callback(userInfo);
} else {
var myInterval = setInterval(function () {
if ($.isFunction(options.callback)) {
console.log('Called dynamically!!');
clearInterval(myInterval);
options.callback(userInfo);
}
}, 200);
}
}
var options = {}
RunTemplateFunction(options,{user:122});
options.callback = function(){
console.log("I'm called!!");
}
This will print
Called dynamically!!
I'm called!!
EDIT:
We can also call callback function in following way without setInterval, it will look different but options.callback variable is replaced by template.callMe function and its instantaneous also.
function TemplateRunner(userInfo){
this.callMe = function(cb){
this.templateFunction(cb);
}
this.templateFunction = function(callback){
callback(userInfo);
}
}
var template = new TemplateRunner({user:100})
template.callMe(function(user){
console.log('call me1',user);
});
template.callMe(function(user){
console.log('call me2',user);
})
This will print
call me1 {user: 100}
call me2 {user: 100}
I have a very common question about javascript
i have a globally declared variable but how can a function with that variable pass the value in the globally declared variable then use it in the second function??
var ID;
function test() {
$.getJSON('/Test1/GetTestID', function (test) {
$.each(test, function () {
ID = this["ID"]
alert(ID);
}
})
}
function test1() {
$.getJSON("/TestSite?Test=" + ID; )
}
alert(ID);
test();
test1();
Function test alert the ID but when i declare it Globally it was undeclared.
Can someone help me with this??
Thanks
I think you are expecting getJSON to be synchronous, but it is not. If the calls are dependent you should nest them:
function test() {
$.getJSON('/Test1/GetTestID', function (test) {
$.each(test, function () {
ID = this["ID"]
$.getJSON("/TestSite?Test=" + ID; )
})
})
}
test1 is being called before test has completed its getJSON call
Because getJSON is asynchronous, the proper way do perform what you need is to use the returned ID in the callback of getJSON:
function test() {
$.getJSON('/Test1/GetTestID', function (test) {
$.each(test, function () {
var theId = this["ID"];
alert(theId);
test1(theId);
}
});
}
function test1(id) {
$.getJSON("/TestSite?Test=" + id);
}
test();
Try this first you set you id to Zero
var ID =0;