Passing parameters to callbacks JavaScript - javascript

I would like for a callback function to fire after a click event. Currently I have the JavaScript
$('#btnSubmit').click(function ()
{
$('#testDiv').hide('slow', onComplete('test'));
});
var onComplete = function (t)
{
$('#hiddenDiv').hide();
alert(t);
}
The callback function is supposed to be fired after the hiding of #testDiv. However, the onComplete function fires first. If I remove the parameters on onComplete and just give it a reference and not invoke it, then the function fires at the right time, but I can't pass parameters to it. How can I pass parameters to onComplete and not have it fire before the div is finished hiding?
fiddle here

You have to actually have a anonymous function there wrapping your onComplete():
$('#btnSubmit').click(function () {
$('#testDiv').hide('slow', function () {
onComplete('test')
});
});
Demo here
In the jQUery docs:
complete
Type: Function()
A function to call once the animation is complete.
When adding onComplete() without a wrapping function the function will be called immediately, otherwise you need to reference it just with onComplete, but then you cannot pass your value unless you use .bind() to pass your parameter.

Use anonymous function:
$('#btnSubmit').click(function () {
$('#testDiv').hide('slow', function () {
onComplete('test')
});
});

You can use .bind() :
$('#testDiv').hide('slow', onComplete.bind(null, 'test'));
The first parameter is the value this will have in the onComplete function. All other parameters are the argument list.

Related

(Why) does jQuery .click() require a callback function?

I have the following jQuery code:
function next() {
//some code here
}
function previous() {
//some code here
}
$("#next").click(function(){
next();
});
$("#previous").click(function(){
previous();
});
This works, but this doesn't:
$("#next").click(next());
$("#previous").click(previous());
Why is this happening? Is there a problem in my code, or is this just a thing with jQuery? Note: #next and #previous refer to two buttons in my html file.
The callback should be a reference to the function.
Why $("#next").click(next()); doesn't work?
func() is a function call and not a reference, which is why it is called immediately.
This,
$("#next").click(function(){
next();
});
is a preferable way in case you need to pass arguments.
Else,
$("#next").click(next) //notice just the signature without ()
This works (if the functions next and previous are defined):
$("#next").click(next);
$("#previous").click(previous);
In this case the next and previous are also callback functions, the difference between the two is,
when you call this line
$("#next").click(next()); the function is executed immediately, and you are passing the result of the next function to the eventHandler of jQuery.
and in this case
$("#next").click(next); you are passing the function next to the EventHandler of jQuery.
Btw.: in the jQuery API Documentation (https://api.jquery.com/click/) it shows all parameters for the click function and the required types it states: "...handler Type: Function( Event eventObject ) A function to execute each time the event is triggered. ..."
try like this you will get your answer,
function next() {
//some code here
}
function previous() {
//some code here
}
$("#next").click(next);
$("#previous").click(previous);
working demo jsfiddle Example
What is going on there is a little bit obscured by the syntax of anonymous functions function() { ... }. What you are doing by that is passing a function, without calling it. And I want to explain how this works:
If you have a simple function
function next() { return 5 };
It will simply return the value 5, if you call it from somewhere:
a = next(); // value of a will be 5
But what you can do too, is to pass the whole function to a. This is possible, because functions in JavaScript are actually objects:
a = next;
b = a(); // value of b will be 5
If you look at the syntax, it shows you, that putting parentheses () at the end of a function invokes it, and returns the return value. While the naked string, without parentheses hands you the function itself.
So what is a callback now, and what does click() like to get as a parameter? A callback function is a function, that gets called later; we actually hand it over, to get called later. click() would like to get such a function as parameter, and it should be clear now, that we have to pass the function without parentheses, to enable click() to call it later, instead of just passing a 5 to it.
$("#next").click(next);
So how does then the initial syntax with the anonymous function work?
function() { next(); }
actually wraps your next() into another function, which is anonymous – because it does not have a name – but is working in the same way as a named function. You can even set a variable by it:
a = function() { next(); } // a will be the anonymous function that calls next()
But calling that function a() will return nothing, because the anonymous function does not return a value (To be exactly: every function call in JavaScript is returning at least undefined, but that's a technical detail).
It can even be called immediately by putting parenthesis at the end of it:
a = function() { return next(); }() // value of a will be 5
Adding the return there will make sure, the return value of next() will be passed through the anonymous function.
This should make clear why
$("#next").click(function(){ next(); });
is working, and why
$("#next").click(next());
is not, but
$("#next").click(next);
will be a good solution.
$("#next").click(next); would work. Notice parenthesis are not required as the function/callback handler should be passed as a parameter.

jQuery promise .done() is firing immediately, not waiting for server to return

I'm trying to use the .done() event of the promise returned from my $.post() function. The server-side function it's calling takes five seconds to return. The problem is the .done() event is firing immediately, as if it's already done. See my code below. If I define a success function in-line with the .post() call it works correctly, it's only the .done() event on the promise object that goes right away. Any idea what I'm missing?
$(document).ready(function () {
$("img.spinner").hide();
var hideSpinner = function (img) {
$(img).hide();
}
$("button.Update").click(function () {
var img = $(this).siblings("img.spinner").show();
var promise = $.post('/MyFunc/Func',
function(){
$(img).hide();
}
);
promise.done(hideSpinner(img));
});
})
That's because hideSpinner(img) calls the hideSpinner function. It is a function call, not a reference to a function. Try this:
promise.done(function () {
hideSpinner(img)
});
You need to pass a function reference to done... instead you are invoking the hideSpinner function and passing the value returned by it as the done callback.
promise.done(function(){
hideSpinner(img)
});

JQuery, Function orchestration

I am stuck on jQuery 1.4.3 on a current project and need some advice on how best to orchestrate the following..
Let's say I have two functions whom both perform ajax calls, and I only want to call the second one if the first one succeeds. With that said, there are also times in my application where I will call function a without needing to call function b. Therefore it wouldn't make sense to put the call to the second function within the first functions success method.
I'd like to do something like,
function doStuff(){
functionA().success( functionb() ).failure();
}
I typically orchestrate by using .done(); but that was introduced in jQuery 1.5, and again I am stuck on 1.4.3 for now.
Sure it makes sense to call it in the functionA() success handler. Just call it conditionally.
// Set a variable to determine if you will need to call functionB()
var youNeedToCallFunctionB = true;
// And call functionA()
functionA();
// Function definition:
function functionA() {
$.ajax({
url: ...,
success: function() {
if (youNeedToCallFunctionB) {
// Call functionB() in the success handler when needed...
functionB();
}
}
});
}
functionB() {
// Some other AJAX call...
}
Even better, pass a parameter to functionA() which determines whether or not to call functionB()
functionA(youNeedToCallFunctionB) {
// same thing as above, but pass the parameter
}
// Called as
functionA(true);

how to call a function with passing parameter?

i want to pass the event to function in javascript suppose. i am fire function from two input. then how i can call the event with passing parameter.
can i do this using calling and without binding event in jQuery.
I'm not exactly sure what you're asking, but here's an example of passing a function with parameters as a callback:
setTimeout(function() {
return myFunction(false, 3);
}, 1000);
You wrap your function call in an anonymous function wrapper.
Example:
function DoCSSStuff(param1,param2)
{
$(param1).css('height', param2);
};
That way you could call the css function to manipulate height with passed parameters.

passing arguments to click function in jquery fires the function without clicking

Hi
I have a function that makes ajax calls once an element is clicked. I use this code:
$(document).ready(function()
{
function ajax_call(offset, length) {
$.ajax({method: "get",
url: "file.php",
data: "offset="+ offset,
success: function(returnedData)
{
$("#content").html(returnedData);
}
});
}
$("#profile").click(ajax_call(0, 1000));
});
The issue is with this line:
$("#profile").click(ajax_call(0, 1000));
When I pass arguments to ajax_call function, the function is run once the page loads without any user intervention, however when I remove the arguments like this:
$("#profile").click(ajax_call); the function is called only when the element is clicked. I have researched for hours about this issue but with no luck
This will call the function immediately ajax_call(0, 1000) and pass the return value as event handler.
You have to wrap it in an anonymous function:
$("#profile").click(function() {
ajax_call(0, 1000);
});
Whenever you have functionname() you are actually calling the function. functionname instead (without parenthesis) gives you a reference to the function. As you cannot just pass ajax_call to click, you have to wrap it in another function.
So the anonymous function function(){...} is passed as event handler and when it gets called, it executes ajax_call(0, 1000).

Categories

Resources