jQuery with Callback and Complete - javascript

So I want to use a callback function within .fadeOut() after it complete's the animation. I can do this successfully using the following, no problem. Works just like I want (The HTML and CSS are just a single black square div)
function fadeOutThing(speed, callback) {
$('div').parent().fadeOut(speed, function() {
if (typeof callback === "function") {
callback();
}
});
}
function OtherThing() {
console.log("hello");
}
fadeOutThing(5000, OtherThing);
What I really want is for that callback function have its own argument, which could be another callback function, like the following. The problem is that when I do this, the log will display before the animation is complete: Here's the fiddle
function fadeOutThing(speed, callback) {
$('div').parent().fadeOut(speed, function() {
if (typeof callback === "function") {
callback();
}
});
}
function OtherThing(stuff) {
console.log("hello" + stuff); //This displays too soon!
}
fadeOutThing(5000, OtherThing(' stuffsss'));
Why is this happening? What am I not understanding?

The issue is because you call OtherThing() immediately on load of the page. This means you're giving the result of the OtherThing() function as the callback parameter, not the reference to the function.
To do what you require you can provide an anonymous function to the callback which wraps your OtherThing() call:
fadeOutThing(5000, function() {
OtherThing(' stuffsss'));
});

Bind the argument instead of calling the function as follows:
fadeOutThing(5000, OtherThing.bind(this,' stuffsss'));

Your are using/calling function in attribute so instead of function declaration you send its return in this case is no return so:
fadeOutThing(5000, OtherThing(' stuffsss'));
equals
fadeOutThing(5000, notDeclaredNothing); //undefined variable
To send function declaration and set paramaters you could do for example third paramater:
function fadeOutThing(speed, callback,attrs) {
$('div').parent().fadeOut(speed, function() {
if (typeof callback === "function") {
callback(attrs); //use with attributes
}
});
}
usage:
fadeOutThing(5000, OtherThing,'stuffsss');
Or second option is to use bind - bind creates new function with given this and given attributes:
fadeOutThing(5000, OtherThing.bind(this,'stuffsss'));
This in global scope is window object.

Related

How to implement a callback in Javascript onload event

I really don't understand... I'm a beginner in Javascript.
I have attached my function onLoadDocument to the document.onload event.
The callback function absolutely have to be executed after function111() and function222() have totally finished their job.
Actually, the callback is executed too soon and it causes a problem to function111 and function222.
How to execute the callback function ONLY when function111 and function222 will have finished their job?
function onLoadDocument(event, callback) {
function111();
function222();
callback();
}
function after() {
firstOpeningWindow = false;
}
document.onload = onLoadDocument(event, after);
The issue is that a callback is a function reference, but this line:
onLoadDocument(event, after)
is a function invocation and therefore runs immediately. Also, it's window that has a load event, not document.
function onLoadDocument(callback) {
function111();
function222();
callback();
}
function after() {
firstOpeningWindow = false;
}
// You have to supply a function reference here. So, to pass arguments
// you'd need to wrap your function invocation in another function that
// will be the callback
window.onload = function() { onLoadDocument(after) };
The problem is that window.onload (as a commenter on another answer said,, document.onload doesn't exist) takes a function, which is executed when the event happens. You're not passing in a function here, you're passing in the return value of onLoadDocument(event, after). This is undefined - and to get that, the browser is executing the function, which is too early for you.
The solution is just to have onLoadDocument return a function:
function onLoadDocument(event, callback) {
return function () {
function111();
function222();
callback();
}
}
function after() {
firstOpeningWindow = false;
}
window.onload = onLoadDocument(event, after);
The function is called when you call the function, so:
document.onload = onLoadDocument(event, after);
… calls onLoadDocument immediately and assigns the return value to onload (which is pointless because the return value is not a function).
If you want to take this approach, then you need to write a factory which generates your onload function using a closure:
function onLoadDocumentFactory(callback) {
function onLoadDocument(event) {
function111();
function222();
callback();
}
return onLoadDocument;
}
function after() {
firstOpeningWindow = false;
}
document.onload = onLoadDocument(after);
That said, it would be easier just to add your functions in order using the modern addEventListener.
function function111() {
console.log(111);
}
function function222() {
console.log(222);
}
function after() {
console.log("after");
}
addEventListener("load", function111);
addEventListener("load", function222);
addEventListener("load", after);

javascript callback, how does it work?

I'm trying to make a callback function, and i can't find a solution to pass an argument in this callback ..
var chrome = {
enterprise: {
deviceAttributes: {
getDirectoryDeviceId: function() {
return "test";
}
}
}
};
chrome.enterprise.deviceAttributes.getDirectoryDeviceId(function(deviceid) {
alert(deviceid);
});
How can the deviceid in the callback function be "xxx" ?
Many thanks
You are passing a function into getDirectoryDeviceId when you call it...but not calling that function or accepting it as an argument
Try:
var chrome = {
enterprise: {
deviceAttributes: {
getDirectoryDeviceId: function(callback) {
// ^^ function you already pass in when you call method
// call the callback you pass in below
callback("test");
}
}
}
};
// nothing changed here
chrome.enterprise.deviceAttributes.getDirectoryDeviceId(function(deviceid) {
alert(deviceid);
});
First, chrome.enterprise.deviceAttributes.getDirectoryDeviceId is being assigned a function that takes no arguments, so you'd need to set one up there.
Then, when you call getDirectoryDeviceId the function that you pass can be executed by appending () to the argument.
Lastly, if you want to be able to pass an argument that the callback will use, you need to set up a second argument in the function.
var chrome = {
enterprise: {
deviceAttributes: {
getDirectoryDeviceId : function(callback, data){
callback(data);
}
}
}
};
chrome.enterprise.deviceAttributes.getDirectoryDeviceId(function (deviceid){
alert(deviceid);
}, "TEST!"); // <-- Second argument is the data that will be used by the callback

How can I write a function accepting callBack function and run it in a 'safe' way?

I want to write such a function:
function doGoodJob(someId, callBackfunction){
// some stuff with someId
// todo: RUN callBackFunction here
}
They say eval is 'dangerous' in terms of code injection.
so, what is the best practice to write a JavaScript function that accepts a call-back function and runs it securely?
Is your callback a string or an actual function ?
If its a function..
function doGoodJob(someId,callbackFunction)
{
callbackFunction();
}
doGoodJob(1,function(){alert('callback');});
If its a string you can use the Function constructor.
function doGoodJob(someId,callbackFunction)
{
var func = new Function(callbackFunction)
func();
}
doGoodJob(1,"alert('test');");
Or test for both..
function doGoodJob(someId,callbackFunction)
{
var func = (typeof callbackFunction == 'function') ?
callbackFunction : new Function(callbackFunction);
func();
}
doGoodJob(1,function(){alert('callback');});
doGoodJob(1,"alert('test');");
This should work:
function doGoodJob(simeOd, callBackFunction){
/** Do stuff **/
callBackFunction();
}
quick fiddle: http://jsfiddle.net/pS67X/
though late to this topic, just wanted to adde some thing.
Above solution works for alert or passing function as argument, but not in the below case.
doGoodJob(1, "someCallbackFunction");
function someCallBackFunction() {
alert("im called");
}
instead if use eval(callbackFunction) like below
function doGoodJob(someId,callbackFunction) {
var func = (typeof callbackFunction == 'function') ?
callbackFunction : eval(callbackFunction);
func();
}
doGoodJob(1,someCallBackFunction);
doGoodJob(1,"someCallBackFunction");
Callback function means function pass as an argument like we pass variable.
When calling the callback function, we could use it like below:
<script>
function callbackExample(arg1, callback){
alert(arg1);
var x = 10, y = 20;
if (callback && typeof(callback) === "function") {
callback(x+y);
}
}
callbackExample("test", function(res){
alert("This is the callback function..." + res);
});
</script>

JavaScript Callback after calling function

Ok so lets say I have this function:
function a(message) {
alert(message);
}
And I want to have a callback after the alert window is shown. Something like this:
a("Hi.", function() {});
I'm not sure how to have a callback inside of the function I call like that.
(I'm just using the alert window as an example)
Thanks!
There's no special syntax for callbacks, just pass the callback function and call it inside your function.
function a(message, cb) {
console.log(message); // log to the console of recent Browsers
cb();
}
a("Hi.", function() {
console.log("After hi...");
});
Output:
Hi.
After hi...
You can add a if statement to check whether you add a callback function or not. So you can use the function also without a callback.
function a(message, cb) {
alert(message);
if (typeof cb === "function") {
cb();
}
}
Here is the code that will alert first and then second. I hope this is what you asked.
function basic(callback) {
alert("first...");
var a = "second...";
callback(a);
}
basic(function (abc) {
alert(abc);
});

Javascript callback function and parameters [duplicate]

This question already has answers here:
Pass an extra argument to a callback function
(5 answers)
Closed 6 years ago.
I want to something similar to this:
function AjaxService()
{
this.Remove = function (id, call_back)
{
myWebService.Remove(id, CallBack)
}
function CallBack(res) {
call_back(res);
}
}
so my calling program will be like this:
var xx = new AjaxService();
xx.Remove(1,success);
function success(res)
{
}
Also if I want to add more parameters to success function how will I achieve it.
Say if I have success function like this:
var xx = new AjaxService();
//how to call back success function with these parameters
//xx.Remove(1,success(22,33));
function success(res,val1, val2)
{
}
Help will be appreciated.
Use a closure and a function factory:
function generateSuccess (var1,var2) {
return function (res) {
// use res, var1 and var2 in here
}
}
xx.Remove(1,generateSuccess(val1,val2));
What you're passing here is not the generateSuccess function but the anonymous function returned by generateSuccess that looks like the callback expected by Remove. val1 and val2 are passed into generateSuccess and captured by a closure in the returned anonymous function.
To be more clear, this is what's happening:
function generateSuccess (var1,var2) {
return function (res) {
// use res, var1 and var2 in here
}
}
var success = generateSuccess(val1,val2);
xx.Remove(1,success);
Or if you prefer to do it inline:
xx.Remove(1,(function(var1,var2) {
return function (res) {
// this is your success function
}
})(val1,val2));
not as readable but saves you from naming the factory function. If you're not doing this in a loop then Xinus's solution would also be fine and simpler than my inline version. But be aware that in a loop you need the double closure mechanism to disconnect the variable passed into the callback function from the variable in the current scope.
You can pass it as anonymous function pointer
xx.Remove(1,function(){
//function call will go here
success(res,val1, val2);
});
one way to do this:
function AjaxService {
var args_to_cb = [];
this.Remove = function (id, call_back, args_to_callback_as_array) {
if( args_to_callback_as_array!=undefined )
args_to_cb = args_to_callback_as_array;
else
args_to_cb = [];
myWebService.Remove(id, CallBack)
}
function CallBack(res) {
setTimeout( function(){ call_back(res, args_to_cb); }, 0 );
}
}
So you can use it like this:
var service = new AjaxService();
service.Remove(1,success, [22,33]);
function success(res,val1, val2)
{
alert("result = "+res);
alert("values are "+val1+" and "+val2);
}
I usually have the callback execute using a setTimeout. This way, your callback will execute when it gets the time to do so. Your code will continue to execute meanwhile, e.g:
var service = new AjaxService();
service.remove(1, function(){ alert('done'); }); // alert#1
alert('called service.remove'); // alert#2
Your callback will execute after alert#2.
Of course, in case of your application, it will happen so automatically since the ajax callback itself is asynchronous. So in your application, you had better not do this.
Cheers!
jrh

Categories