When does an anonymous function execute if defined as a functions parameter? - javascript

//The anonymous function is not being executed there in the parameter.
//The item is a callback function
$("#btn_1").click(function() {
alert("Btn 1 Clicked");
});
If the anonymous function is not being executed in the parameters of the main function, then how do you execute the anonymous function inside the body of the main function?
Something like this:
function myFunction(function(){ /*code inside anon function */ }){ /*Code insider main function */}
/*Calling the main function */
myFunction();
when does anoymous function get executed?

From your edit, it looks like you have the function declaration and the function callback mixed up.
If a function takes another function as a parameter it will look something like:
// myFunction accepts a function as a parameter
function myFunction(fn){
//call the passed in function
fn() // fn is the function you passed in
}
// Calling the main function and pass in function
myFunction(function(){
console.log("hello")
}
);
So in your original example:
$("#btn_1").click(function() {
alert("Btn 1 Clicked");
});
click() is defined to accept a function, which you passed in. It is analogous to myFunction above except the browser waits to get a click before it calls the function you passed in.
So in answer to your original question:
then how do you execute the anonymous function inside the body of the main function?
The answer is, in the case of event handlers like click() you don't, the browser does.

Related

How to use JS callbacks?

I have some really hard times understanding JS callbacks. From what I understand is that JS callback is a function that takes the argument of another function. So let's say I have a function called myFunction and passes mySecond to it, will it exicute myFunction before mySecond?
function myFunction(){
alert("hello");
}
function mySecond(){
alert("world");}
}
myFunction(mySecond);
if you want myFunction before mySecond. The code is below.
function myFunction(func){
alert("hello");
func();
}
function mySecond(){
alert("world");}
}
myFunction(mySecond);
Hello, if you want myFunction after mySecond. The code is below.
function myFunction(func){
func();
alert("hello");
}
function mySecond(){
alert("world");}
}
myFunction(mySecond);
a JS callback is a function that takes the argument of another function
This "understanding" is confused and has it backwards:
a JS callback is a function provided as an argument to another function, to be called back after the called function has done something.
A classic example or callback function is provided by the syntax of setTimeout:
setTimeout( callback, 1000);
Here callback (a function) is called back (by setTimeout) after a second has elapsed.

Calling jQuery event handler on click : anonymous vs named function behaviour

Playing around with the .on('click', ) event and I get differing behaviour based on whether I supply an anonymous vs named function (the named function doesn't work). Is this a syntax error?
<div id="myID"> abc </div>
<script>
$("#myID").on('click',function(e){
console.log(e.type);
}); //works
function handle(e){
console.log(e.type);
}
$("#myID").on('click',handle(e)); //doesn't work
</script>
You need to replace
$("#myID").on('click',handle(e));
with
$("#myID").on('click',handle);
When you call a function, it is executed immediately. This happens when you do
$("#myID").on('click',handle(e));
You call the function, passing an event e which does not exist yet. What you want instead is giving jQuery a function that it should call when the user clicks on the element with the id myID.
This is possible in JavaScript because it has first-class functions. This means that if you create a function like this:
function handle(e){
console.log(e.type);
}
then you get a reference to the function that you just created. This reference is stored in a variable named handle. You could achieve the same if you do:
var handle = function (e) { // create a function and store a reference to it in a variable
console.log(e.type);
};
The function takes an argument e. This doesn't exist yet, it has to exist in the moment you call the function:
handle(e); // ReferenceError: e is not defined
You can pass the reference to that function to jQuery, which then calls your function when the user clicks the element. At that point, e still doesn't exist, because it will contain information about the event, which hasn't occured yet. It will look like this:
$("#myID").on('click', handle); // pass a reference to the handle function to jQuery
Now, handle doesn't get called, because you only pass a reference to the function. You could say that you pass the function as an argument to another (jQuery) function. This is called a callback function.
Edit
Note that all functions that were created above take e as their argument. The argument doesn't have to exist in the very moment you create the function. However, when you (or jQuery) call the function, you have to provide an argument so that the function can do its job.
It's the same with an unnamed function: you create the function, but the argument does not exist yet. When you (or jQuery) call the function, you have to provide an argument.
This means there is no essential difference. The only difference is that one function has a name, the other one doesn't. You could even do this:
$("#myID").on('click', function handle (e) { // pass a reference to the function, but do not call it
console.log(e.type);
});
... which has the same effect as:
$("#myID").on('click', function (e) { // pass a reference to the function, but do not call it
console.log(e.type);
});
... except that in the first example, you keep a reference to the function that you created in a variable called "handle". In the second example, you lose the reference to the function, and only jQuery will be able to use your function.
Edit end
Another example for that would be:
var testFunction = function (arg) {
console.log('My argument is:', arg);
};
var executeTwoTimes = function (callback) { // accept a callback function as the first argument
callback('foo'); // execute the callback function
callback('foo');
};
executeTwoTimes(testFunction); // pass a reference to testFunction
// or:
executeTwoTimes(function (a) { // pass a reference to an anonymous function
console.log(a + ' bar');
});
I hope I could make things clearer for you.

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.

Function getting called on the load of page

for (var key in obj[i]) {
dataDump[key] = textField.value;
var callback = function(zeKey){
return function(e){
dataDump[zeKey] = e.source.value;
};
}(key);
textField.addEventListener('change', callback);
}
When I load the window, this function gets called automatically, which I don't want and instead I want this to be called only when I do a change.
The main point is calling function(zeKey){...}(key). When you do so, key, which is a string is copied as a parameter (zeKey) to your anonymous function.
The following
var callback = function(zeKey){
return function(e){
dataDump[zeKey] = e.source.value;
};
}(key);
Calls the anonymous function with argument zeKey.
This anonymous function returns another function. This returned function is assigned to the callback.
If 1 what you mean by "the function is getting called" then this is expected behavior.
This entire code should be called only after DOM is ready. Place all these in a function and make sure the function is called only on window.onload or (jQuery's) .ready()
The function returned by the function will be called only during the callback.
Add these code once dom is created. If above code is inside a function, attach to window.load or write these code at the end of page.

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