Pass a function as parameter in jQuery? - javascript

I would like to pass to a jQuery function a regular function, instead of the usual anonymous function, but I'm not sure how such a thing could be done.
Instead of this:
function setVersion(feature) {
$.post("some.php", { abc:"abc" },
function(data){
// do something here
}, "json");
}
I would like to do this:
function foo(data){
// do something here
}
function setVersion(feature) {
$.post("some.php", { abc:"abc" }, foo, "json");
}
Thank you.

Yeah, already works. But you want it probably look like this:
function setVersion(feature, myFunction) {
$.post("some.php", { abc:"abc" }, myFunction, "json");
}
setVersion(blah, foo);

Should run just fine.
I believe jQuery is actually meant to use the regular function, called by name. Using the anonymous function is simply a replacement for a named function that would otherwise be passed.

Yes, that is exactly how you do it.

Related

My call on function wont work? [duplicate]

I have a jQuery onClick handler, writed with an anonymous function like that:
$("#selector").on("click" function(){
// do something
})
I would generalize the anonymous function extracting the logic in a named function, that drive me to something like:
$("#selector").on("click" namedFunction())
function namedFunction(){
// do something
}
To me seemed a good solution. But there's a drawback since the namedFunction is executed as soon script is loaded. Here you can test the bad behaviour.
Just pass the reference of that function itself.
Try,
$("#selector").on("click", namedFunction);
You don't need the () for your function here:
$("#selector").on("click", namedFunction)
Or a shorter version
$("#selector").click(namedFunction);
To pass custom parameters to namedFunction use:
$("#selector").on("click", null, {param1: param1}, namedFunction);
namedFunction(event) { console.log(event.data.param1); }
try like
function namedFunction(){
alert("Hello world!")
}
$("#clickTester").on('click', namedFunction)
Updated Fiddle
Named function[view jsFiddle]
Function namedFunction () {
alert("Hello world!");
}
$("#clickTester").on('click', namedFunction);
Anonymous function [view jsFiddle]
$("#clickTester").click(function(){
alert("Hello world!");
});

Meteor how to call another function in current function?

I have a function in helpers. I want to call that function in my next function. How can I fall it ?
'first_func' ()
{
return "hello";
},
'second_func' ()
{
return this.first_func();
}
This is not working. I want to call first function in second one.
Thank YoU!
With the way you're trying to do this, you would not need this. So you would be able to call the first function like so:
function first_func() {
//`this` is bound to first_func()
return "hello";
}
function second_func () {
//`this` is bound to second_func()
return first_func();
}
second_func(); // returns 'hello'
It appears, however, that you're trying to call functions within a class or a method. I can't guess at how or why, though, so please see the answer at Can you write nested functions in JavaScript?
Like #thatgibbyguy says, you can just define a function in the same file and use it. In a Meteor template helper, this is the data context of the helper, not the template instance itself.
Template.myTemplate.helpers(
first_func(){
return myFunction();
},
second_func(){
return myFunction();
}
);
function myFunction(){
return "Hello"
}
You can also register a global helper which can be used from any template

Execute dynamic function with param in javascript

If the following possible?
I wish to move the alert(result) into a function and to dynamically call it.
Current
$.ajax(this.href, {
success: function (result)
{
alert(result);
AjaxComplete();
}
});
My Attempt - not working
$.ajax(this.href, {
success: function (result)
{
window["MyAlert(result)"]();
AjaxComplete();
}
});
function MyAlert(result)
{
alert(result);
}
Is this possible?
Why can't you just do this?
MyAlert(result);
If MyAlert is a part of the window object, it's already a global.
Unless you want to call an arbitrary function by name (which isn't really good practice, IMO), which you can do like this:
window[function_name_string](argument);
window["MyAlert(result)");
is invalid syntax (missmatching [ and ), wrong function name, and not calling it at all, just getting it..). Should be
window["MyAlert"](result);
if you want to call it like that, but I see no reason why you couldn't just call it normally, as Blender mentioned.

Passing parameters to a javascript callback function [duplicate]

This question already has answers here:
Pass an extra argument to a callback function
(5 answers)
Closed 6 years ago.
I've been trying to work out how to pass additional parameters to a javascript callback function.
In similar posts users have succeeded using anonymous function (these are new to me so I may have been doing them wrong) but I just can't get them to fire.
The below is what I have now, I need to be able to pass the itemId to the function "ajaxCheck_Callback" as well as the response.
Hope this makes sense.
Thanks for the help.
function delete(itemId)
{
selectpage.ajaxCheck(itemId, ajaxCheck_Callback);
}
Function ajaxCheck_Callback(response)
{
alert(response);
alert(itemId);
}
Thanks for the help guys. I now get undefined on my alert whereas previously this was alerting correctly.
function delete(itemId)
{
selectpage.ajaxCheck(itemid, function () {ajaxCheck_Callback(itemid); });
}
function ajaxCheck_Callback(response)
{
alert(response);
alert(itemId);
}
The way is usually done is to use an anonymous function.
function deleteItem(itemId) {
selectpage.ajaxCheck(itemId, function() { ajaxcheck_Callback(itemId); });
}
function ajaxCheck_Callback(response)
{
alert(response);
}
Careful with your syntax, there are some errors in there. The function keyword has a lower-case f and you can't have a function named delete, that's a reserved keyword.
As your question mentions, you can do it using an anonymous function:
function deleteItem(itemId)
{
selectpage.ajaxCheck(itemId, function ()
{
ajaxCheck_Callback(itemId);
});
}
// Note, lowercase 'f' in 'function'
function ajaxCheck_Callback(response)
{
alert(response);
}
It can also be done using a named function, which you might find more readable:
function deleteItem(itemId)
{
function onAjaxCheck()
{
ajaxCheck_Callback(itemId);
}
selectpage.ajaxCheck(itemId, onAjaxCheck);
}
N.B. as #Xeon06 points out, delete is a reserved word, so that is not a valid function name.
Create an anonymous function, which calls your callback, and supplies the needed parameter.
function deleteItemById(itemId)
{
selectpage.ajaxCheck(itemId, function() { ajaxCheck_Callback(itemId); });
}
The anonymous function will create a closure over itemId, and therefore will still have access to this value even after the original call to delete has long since ended.
For completeness, also note that delete is a reserved word in JavaScript; you need to name this function something else.

Inline functions and other method's scope

How do I make the myFunction visibile for the in-line function in .ready() event?
$(document).ready(function() {
...stuffs...
myFunction(par1, par2, anotherFucntion_callback);
}
);
function anotherFunction_callback(data) {
..stuffs..
}
I didn't quite catch your question. Do you mean that you want to pass "myFunction_callback(data)" as the last argument in your:
myFunction(par1, par2, anotherFunction_callback);
, including that "data" parameter?
In that case the solution is pretty standard, write this before that one:
var temp = function() { anotherFunction_callback(data) };
an alternative syntax is:
function temp() { myFunction_callback(data) };
// even though this looks just like a free function,
// you still define it inside the ready(function())
// that's why I call it "alternative". They are equivalent.
In general, if you want to pass a function with 1 or more arguments to another function, you use that format. Here, we basically create a new no-argument function that calls another. The new function has access to the "data" variable. It's called "closure", you may want to read more on that.
Of course, if the callback require no argument, you can just use the original function name.
I hope this helps.
ps: You can even inline the function declaration, making it anonymous, like so:
myFunction(par1, par2, function() { myFunction_callback(data) });
Notice that the
$(document).ready(function() {});
looks pretty much just like that.
You use the actual name of the function, i.e. myFunction_callback instead of myFunction or anotherFucntion_callback.

Categories

Resources