Store jQuery scripts in JS Variable - javascript

I have a function with a variable called callback
function test(callback){
// Some code
callback;
}
When I call this function I used to insert a one liner into callback
eg. test($('#elem').hide());
Now I want to put multiple lines in here as the callback. I tried this but it does not appear to work.
var resetc = function(){
$('.access').removeClass('viz');
window.setTimeout(function(){
$('.access').find('.input.wheel').removeClass('viz');
$('.access').find('input').removeAttr('disabled');
},1000);
}
test(resetc);

As you are passing the function reference. You can use the callback variable to execute the function which it is referring. like
function test(callback) {
// Some code
callback();
}
You statement test($('#elem').hide()); is having no effect as you are passing the output of $('#elem').hide() to your method test and statement callback; actually is not performing anything.
You need to change your function call for test($('#elem').hide()); with
test(function() {
$('#elem').hide();
});

Your initial code doesn't do what you think. To call a callback, you need to put () after it:
function test(callback) {
// some code
callback();
}
If you fix that, test(resetc); will do what you want.
The reason you didn't notice this in your first test is because when you write
test($('#elem').hide());
you're executing $('#elem').hide() before calling test, it's not being done when test runs the callback. You need to pass a function to defer the execution until the callback is called:
test(function() {
$('#elem').hide();
});

Related

Function with a callback

Learning javascript and wanted to get more clarity regarding callbacks.
In the following code snippet,
function do_a( callback ){
// if callback exist execute it
callback && callback();
}
function do_b(){
console.log( 'do_b executed' );
}
//one way
do_a( function(){
do_b();
});
//other way
do_a(do_b);
Is there a difference between the two ways the do_a() is called. One passes a pointer to the do_b function, the other passes a function which executes the do_b function. All the examples i've seen use the first way. Is that more preferred style wise?
The first way just creates an extra anonymous function that calls the second function. This is useful if you want to perform actions before or after calling the callback, e.g.
do_a( function(){
console.log("I'm going to call the second function...");
do_b();
console.log("Second function is done.");
});
Otherwise, I can't see any point in this extra function and the second way is better.
you don't have to pass it as an argument. Directly call it.
function abc(){
a = "function abc";
console.log(a);
cde();
console.log(a);
}
function cde(){
a="function cde";
}
abc();

how to call function-1 inside function-2

I have function-1
$('.make_favorite').live('click', function() {
//some code here
});
I have another function-2
function selectContactTab() {
//some code here
//call function-1 here
}
for some reason I do not have control over function-1,
My Question is how to call function-1 inside function-2?
You can manually fire the click event, which will result in the anonymous function, what you state as Function-1, being run...
function selectContactTab() {
//some code here
//call function-1 here
$('.make_favorite').click();
}
Your Function-1 is actually function call, with a callback passed in. You need to wrap it inside it's own function, something like this:
function functionOne() {
//some code here
}
function selectContactTab() {
//some code here
functionOne();
}
$('.make_favorite').live('click', functionOne);
In this example, functionOne is a function on the scope, and is also being passed in as the callback for your .live call. The reason it didn't work before was because the callback in your function-1 was outside of the scope your function-2 was in - put simply, it didn't exist. Initialising it in a function like in my example will make it available to call.

setTimeout nuances in Node.js

I'm trying to understand how the callback function works inside the setTimeout function. I'm aware the format is: setTimeout(callback, delay) I wrote a little test script to explore this.
test1.js
console.log("Hello")
setTimeout(function () { console.log("Goodbye!") }, 5000)
console.log("Non-blocking")
This works as expected, printing Hello <CRLF> Non-blocking and then 5 seconds later, prints Goodbye!
I then wanted to bring the function outside of the setTimeout like this:
console.log("Hello")
setTimeout(goodbye(), 5000)
console.log("Non-blocking")
function goodbye () {
console.log("Goodbye")
}
but it doesn't work and there isn't a 5 second delay between Non-blocking and Goodbye!, they print straight after each other.
It works if I remove the brackets from the function call in the timeout, like this:
setTimeout(goodbye, 5000)
but this doesn't make sense to me because that's not how you call a function. Futhermore, how would you pass arguments to the function if it looked like this?!
var name = "Adam"
console.log("Hello")
setTimeout(goodbye(name), 5000)
console.log("Non-blocking")
function goodbye (name) {
console.log("Goodbye "+name)
}
My question is really, why doesn't it work when there are parameters in the function, despite the fact the setTimeout is being provided with a valid function with the correct syntax?
By putting the parentheses after your function name, you are effectively calling it, and not passing the function as a callback.
To provide parameters to the function you are calling:
You can pass an anon function. setTimeout(function(){goodbye(name)}, 5000);
Or, you can pass the arguments as a third parameter. setTimeout(goodbye, 5000, name);
Look at this question: How can I pass a parameter to a setTimeout() callback?
No matter where you place it, goodbye(name) executes the function immediately. So you should instead pass the function itself to setTimeout(): setTimeout(goodbye, 5000, name).
When you use it like this:
setTimeout(goodbye(), 5000);
it will first call goodbye to get its return value, then it will call setTimeout using the returned value.
You should call setTimeout with a reference to a callback function, i.e. only specifying the name of the function so that you get its reference instead of calling it:
setTimeout(goodbye, 5000);
To make a function reference when you want to send a parameter to the callback function, you can wrap it in a function expression:
setTimeout(function() { goodbye(name); }, 5000);
You can use parantheses in the call, but then the function should return a function reference to the actual callback function:
setTimeout(createCallback(), 5000);
function createCallback() {
return function() {
console.log("Goodbye");
};
}

Javascript Callback functions vs just calling functions

So i don't really understand the point of "callback".
Here is an example of callback:
function sayBye(){
alert("Bye!");
}
function saySeeYou(){
alert("See you!");
}
function sayHello(name,myfunc){
alert("Hello");
myfunc;
}
sayHello("Max",saySeeYou());
Whats the point of passing in a function when you can just call the function? like this code does the exact same:
function sayBye(){
alert("Bye!");
}
function saySeeYou(){
alert("See you!");
}
function sayHello(name){
alert("Hello");
saySeeYou();
}
sayHello("Max");
Whats the point of passing in a function when you can just call the function?
Usually, callbacks Javascript are used in Javascript for code that you want to run in the future. The simplest example is setTimeout: if you call the callback now then the code runs immedieately instead of after 500 ms.
//prints with a delay
console.log("Hello");
setTimeout(function(){
console.log("Bye");
}, 500);
//no delay this time
console.log("Hello");
console.log("Bye");
Of course, it would be really neat if we could write something along the lines of
//fake Javascript:
console.log("Hello");
wait(500);
console.log("Bye");
But sadly Javascript doesnt let you do that. Javascript is strictly single-threaded so the only way to code the wait function would be to pause the execution of any scripts in the page for 500 ms, which would "freeze" things in an unresponsive state. Because of this, operations that take a long time to complete, like timeouts or AJAX requests usually use callbacks to signal when they are done instead of blocking execution and then returning when done.
By the way, when passing callbacks you should only pass the function name. If you add the parenthesis you are instead calling the function and passing its return value instead:
//When you write
foo(10, mycallback());
//You are actually doing
var res = mycallback();
foo(10, res);
//which will run things in the wrong order
Your code is not correct as Felix Kling already pointed out. Besides this, passing a function instead of calling one directly allows you to insert different behavior, your code is more decoupled and flexible. Here an example:
function sayBye(){
alert("Bye!");
}
function saySeeYou(){
alert("See you!");
}
function sayHello(name,myfunc){
alert("Hello");
if (myfunc) {
myfunc();
}
}
sayHello("Max",saySeeYou);
// I'm inserting a different behavior. Now instead of displayng "See you!"
// will show "Bye!".
sayHello("Max",sayBye);
You are doing it wrong, you should do like bellow
Don't call the function just pass the function as callback
use this
sayHello("Max",saySeeYou); //here the second parameter is function
instead of
sayHello("Max",saySeeYou());//This will put the result of saySeeYou as second parameter
in say hello call the functiom
function sayHello(name,myfunc){
console.log("Hello");
myfunc();
}

javascript callback question

I have a javascript which I didn't write but I need to use it ..
function function1()
... body..
and at the end
I have this
'callback': 'getListCallback'
}
What does this callback mean and getListCallback = function(obj) is another function, does this mean that results from function1 are returned to function getListCallback?
Tnx
A callback function is a function that is going to be called later, usually when some event occurs. For example, when adding an event listener:
function callback(){
alert("click");
}
document.body.addEventListener("click", callback, true);
In many cases you pass the callback function as an anonymous function:
setTimeout(function(){alert("It's been 1 second");}, 1000);
The code getListCallback = function1(obj); will not call getListCallback with the results of function1(obj). It will store whatever function1(obj) returns into getListCallback. If function1 returns a function, then you can call that function later, like so:
function function1(obj){
return function(){
alert("getListCallback was called. obj = "+obj);
}
}
getListCallback = function1(1);
getListCallback();
Yes, it should mean that
normally a callback function means a function which will call after current function execution finished.
This
getListCallback = function(obj){// do something} is like assigning this "function(obj){//....}" to a variable which can use in any place where you need to use that function.

Categories