Javascript callback functions execution - javascript

I'm not sure the correct term for this. But I want to write a function that accepts another function and execute it.
For eg.
function test(data, aFunc) {
var newData = data + " Shawn";
aFunc.call(newData);
}
test("hello", function(data){
alert(data);
});
Data is supposed to contain "hello Shawn" string. Help me rewrite this the correct way please.

The first argument of the call method is used to set the this keyword (the function context) explicitly, inside the invoked function, e.g.:
function test(data, aFunc) {
var newData = data + " Shawn";
aFunc.call(newData);
}
test("hello", function () {
alert(this); // hello Shawn
});
If you want to invoke a function without caring about the context (the this keyword), you can invoke it directly without call:
function test(data, aFunc) {
var newData = data + " Shawn";
aFunc(newData); // or aFunc.call(null, newData);
}
test("hello", function (data) {
alert(data);
});
Note that if you simply invoke a function like aFunc(newData); or you use the call or apply methods with the this argument set as null or undefined, the this keyword inside the invoked function will refer to the Global object (window).

Looks fine but you can just change
aFunc.call(newData);
to
aFunc(newData);

You were close. The first argument to "call" is the "scope" argument. In this case, it doesn't matter what it is, because you're not using "this" anywhere in your anonymous function, so any value will suffice.
function test(data, aFunc) {
var newData = data + " Shawn";
aFunc.call(this, newData);
}
test("hello", function(data){
alert(data);
});

Related

JS - Calling function from function not working

I have a function that gets called, and in it, I call another function called:
updatePerson(name)
For some reason it never activates when the function below is called. Everything else in the function works.
function updateName(name) {
$.get('XXX',function (data) {
var results = $.parseJSON(data);
var matchName = String(results.data[0].first_name);
updatePerson(matchName);}
);
};
Has anyone got an idea what I am doing wrong?
If I run alert(matchName) I get Nick as a response.
If I run console.log(updateMap(matchAddress)) I get undefined
It could do with the fact that you're passing a parameter from a callback function. In Javascript, variables inside a Callback are not available outside the callback.
Try setting the value of String(results.data[0].first_name) to a variable declared outside of the updateName function (i.e a global variable) and then call the updatePerson function outside of update name, with the globally declared variable as a parameter. Like so
var globalMatchName = '';
function updateName(name) {
$.get('XXX',function (data) {
var results = $.parseJSON(data);
globalMatchName =String(results.data[0].first_name);
}
);
updatePerson(globalMatchName)
}

Call javascript callback

I want to pass an anonymous function as a callback, then call it. I am probably missing something simple, but I just get the error 'Uncaught type error - callback is not a function'.
This is what I am doing - (using jQuery) - I pass the callback as an anonymous function when creating a new object:
$('#someid').alphaColorPicker({
callback: function() {
console.log("called")
}
});
Then I call it at some point (or try to):
$.fn.alphaColorPicker = function(callback) {
...
...
callback(); //this throws the error
}
How do I correctly call the callback function?
Thanks.
Look at the value you are sending:
{ callback: function () { ... } }
That isn't a function.
It is an object with a property called callback which is a function.
Therefore:
callback.callback();
Or you could pass an actual function instead of an object:
$('#someid').alphaColorPicker(function() { console.log("called") });
You are not directly passing the function, you are passing an object which has callback property
make it
$.fn.alphaColorPicker = function(options) {
...
options.callback(); //this throws the error
}
The thing you pass into the alphaColorPicker is not a callback function but rather a object containing a value that is a callback.
{ // When putting it within {} its a new object.
// Where 'callback' is a member/key of the object.
callback : function() {
console.log("called");
}
If you instead pass the function directly:
$('#someid').alphaColorPicker(function() {
console.log("called");
});
You can call it right away via callback();.
If you wish to keep it as an object, you can call it by calling the member of the object instead of trying to call the object as a function:
callback.callback();
Found the problem, should not have passed the function as
callback: function() {
console.log("called")
}
But just like this:
$('#' + boxID).alphaColorPicker(function() {
console.log("hello")
});
And if I want to pass parameters in, I can do it like this:
$('#' + boxID).alphaColorPicker({x:styleName, y:id, callback:function() {
//do something
}});
But I am confused about how to pass parameters in / out like in jQuery event handlers such as:
$("#"+boxID).alphaColorPicker({x:styleName, y:this.inputID}, function(e){}
});
How do you access the callback here? In my example, in alphaColorPicker callback.x and callback.y are obviously available, but the callback function is passed as an object I can't see how to call it.

return success data in require.js with callback

i have a little understanding problem with my current code...
i create a new require js module.
define(['jquery','apiomat'],function($,Apiomat) {
var getLocation = function(data, callback) {
Apiomat.Localization.getLocalizations("locale like 'de'", {
data: data,
onOk: function (data) {
callback(data);
}
});
};
return {
getData: function(data, callback) {
getLocation(data, callback);
}
}
});
And if i try to access these function with:
var test = easy.getData();
app.logger("CALLBACK FROM COMMON: " + JSON.stringify(test));
I always get this error message.
TypeError: callback is not a function. (In 'callback(data)', 'callback' is undefined)
Im not really sure what i have done wrong.
getData takes two arguments. The second one is supposed to be a function, but you aren't passing any arguments at all, so it gets the value undefined.
It then calls getLocation with the same arguments and Apiomat.Localization.getLocalizations does its thing. Eventually getLocalizations (or another function called by it) calls getOK which attempts to call callback.
undefined is not a function, so you get the error message.
Additionally the getData function doesn't have a return statement so will be returning undefined. This means there is no point in assigning the return value to test.
You need to pass a function which does whatever you want to do:
function myCallback(test) {
app.logger("CALLBACK FROM COMMON: " + JSON.stringify(test));
}
… and pass arguments to getData.
easy.getData("some data", myCallback);

How to make JS function wait for JSON data to load?

This works:
function getDataJSON() {
var queryString = "https://www.examplesite.com/someJSON.json";
$.getJSON(queryString, function(data) {
doStuffWithData(data)
});
}
function doStuffWithData(JSON) {
// some code that refers to JSON
}
getDataJSON();
But this complains that a variable (JSON) is undefined somewhere in doStuffWithData():
function getDataJSON(callback) {
// Gets share data and runs callback when received
var queryString = "https://www.examplesite.com/someJSON.json";
$.getJSON(queryString, function(data) {
if(typeof callback === "function") {
callback(data);
}
});
}
function doStuffWithData(JSON) {
// some code that refers to JSON
}
getDataJSON(doStuffWithData());
What am I likely to be doing wrong? The $.getJSON() call takes a second or two so I do need to wait for that and do stuff after it. I think the issue is with the code execution order, but it could be that I've misunderstood how to properly pass the data to the callback function.
It would be better if I could just load the data into a variable all my other functions can access.
This:
getDataJSON(doStuffWithData());
should be this:
getDataJSON(doStuffWithData);
Otherwise it invoked that function immediately and attempts to pass the result of the function into getDataJSON
You need to leave out the parenthesis in this call
getDataJSON(doStuffWithData()); should be getDataJSON(doStuffWithData). The reason is that doStuffWithData is the function and doStuffWithData() is the retrun value from the function.

Why does Javascript need an anonymous function to delay execution?

In my application I need to conduct an IP lookup as a prerequisite to proceeding with execution of another function that needs that data. Originally, I called the function as follows:
$(document).ready(function(){
var ipUrl = "myURL?callback=?";
$.getJSON(ipUrl, function(data) {
window.ip = data['ip'];
console.log("inside function" + window.ip);
}).done(printIp());
});
function printIp() {
console.log("function is done " + window.ip);
}
However, this outputs as
function is done undefined
inside function <ip_address>
I.e. the printIp() function is called before the $.getJSON is actually complete.
If however, I wrap the printIp() call within an anonymous function as follows:
$.getJSON(ipUrl, function(data) {
window.ip = data['ip'];
console.log("inside function" + window.ip);
}).done(function() {
printIp();
});
I get:
inside function <ip_address>
function is done <ip_address>
As I would expect. What is going on here? Why do I need to wrap the function call in an anonymous function?
your code says
}).done(printIp());
what this does is calling printIp and using the result of the function call as an argument to the done method.
what you actually want is passing the function as a done handler. use }).done(printIp); to do this instead.
You are executing printIp right away. Try it without the ():
$.getJSON(ipUrl, function(data) {
window.ip = data['ip'];
console.log("inside function" + window.ip);
}).done(printIp);
pass the function without parantheses, otherwise you are calling it right away:
.done(printIp)

Categories