Given an <input id="foo"> element, I want to call an existing function on blur and pass an anonymous callback to it.
Case 1, simple function call:
function bar(){
alert("I am");
}
$("#foo").blur(bar); //Works fine
Case 2, passing arguments/function:
$("#foo").bind("blur", {func: function(){console.log("I am apple")}}, bar);
function bar(event){
event.data.func(); //Works fine
};
Problem with case 2 is that I'd like to have bar() as a generic function called by more than blur, in which case I would be passing anonymous function directly, not "baked" into a data object. So ideally like this:
function bar(callback){
//Do stuff
callback();
}
bar(function(){console.log("Hello Earth")}); //Works
$("#foo").blur(bar(function(){console.log("Hello world")})); //Doesn't work
Last line doesn't work as function gets executed directly, but it's an example of what I would like to achieve. I guess I possibly could make some typeof checks in bar() to determine what I am receiving, but I wanted to ask if there's a cleaner way to pass anonymous function on blur, instead of changing bar().
...I wanted to ask if there's a cleaner way to pass anonymous function on blur, instead of changing bar().
Not sure quite what you mean by that, you will have to either change bar or wrap bar.
Changing it:
Make bar a handler generator rather than a direct handler:
function bar(callback) {
return function(e) {
// You could use `e` (the event) here and/or pass it on to the callback
callback();
// You might use the callback's return, e.g.:
// return callback();
// ...if you wanted it to be able to `return false`
};
}
Now, bar returns an event handler that will call the callback (in addition, presumably, to doing something of its own; otherwise, it's a bit pointless and you'd just pass the callback directly).
Usage:
$("#foo").blur(bar(function(){console.log("Hello world")}));
Wrapping it
If you literally mean you don't want to change bar, you'll need to wrap it:
function wrap(f, callback) {
return function() {
// You could call `callback` here instead of later if you like
// Call the original function passing along the `this` and
// arguments we received (`arguments` isn't pseudo-code, it's
// a pseudo-array JavaScript creates for you), get its return value
var retval = f.apply(this, arguments);
// Call the callback
callback();
// Return the original function's return value
return retval;
};
}
If you want to avoid letting errors thrown by callback to make it to the event mechanism, you can wrap it in a try/catch.
Usage:
$("#foo").blur(wrap(bar, function(){console.log("Hello world")}));
function bar(callback){
//Do stuff
callback();
}
bar(function(){console.log("Hello Earth")}); //Works
$("#foo").blur(bar.bind(this,function(){console.log("Hello world")})); //Will work
Wrap it and return it as an anonymous function:
function bar(callback){
return function() {
callback();
}
}
// direct
bar(function(){console.log("Hello Earth")})();
// as callback
$("#foo").blur(bar(function(){console.log("Hello world")}));
function bar(){
alert("I am blur");
}
$("#foo").bind('blur',bar);
Last line doesn't work as function gets executed directly
$("#foo").blur(bar(function(){console.log("Hello world")}));
On the last line you're passing the result of bar to the blur() function, not bar itself, it's the same as:
var result = bar(function(){console.log("Hello world")});
$("#foo").blur(result);
The standard method is to wrap this in an anon function:
$("#foo").blur(function() { bar(function(){console.log("Hello world")}) });
This means there are no changes to your other existing functions, as per the question requirement: "instead of changing bar()"
Related
I'm perplexed as to why I have to wrap my alert in a function in order to avoid my code ignoring the event listener.
If I run this code, It'll work properly and I'll be able to click and have the alert display after the click
elem.addEventListener('click', (function(numCopy) {
return function() {
alert(numCopy);
};
})(num));
But if I run this code, it'll ignore the event listener and display the alert as soon as the page loads
elem.addEventListener('click', (function(numCopy) {
return alert(numCopy);
})(num));
I could ignore it and just accept this is the way it's done but I would really appreciate it if someone could explain the logic behind this so I can fully grasp the concept, thanks a lot in advance.
Lets figure out what's going on by looking at the following example:
function foo(x) {
return x;
}
var bar = foo(42);
baz(bar);
What is the value passed to baz? 42 because foo simply returns the value passed to it.
Now lets inline the function call:
function foo(x) {
return x;
}
baz(foo(42));
What is the value passed to baz here? Still 42 whether we assign the return value to a variable or directly pass it to the other function doesn't make a difference.
Now lets inline the function definition:
baz(function foo(x) { return x; }(42));
Now we have an IIFE. What is the value passed to baz here? Still 42. We didn't actually change what the code is doing, we just got rid of intermediate variable assignments (we could also drop foo from the function expression).
How does this related to your code? Lets work our way backwards from your code. We start with:
elem.addEventListener('click', (function(numCopy) {
return alert(numCopy);
})(num));
Lets extract the function definition:
function foo(numCopy) {
return alert(numCopy);
}
elem.addEventListener('click', foo(num));
Now lets extract the function call:
function foo(numCopy) {
return alert(numCopy);
}
var bar = foo(num);
elem.addEventListener('click', bar);
Do you see what's wrong here? You are calling the function (foo in this case). The function executes alert and that's why you immediately see the alert.
foo returns the return value of alert (assigned to bar), so you are passing that value to addEventListener.
But alert returns undefined whereas addEventListener expects to be passed a function.
That's why your IIFE needs to return a function.
So basically why do I have to use this kind of method in these kind of situations in particular?
function Example(callback) {
// What's the purpose of both 'call()' and 'null'?
callback.call(null, "Hello")
}
Exemple(function(callback) {
alert();
})
I've figured it out this syntax in a open project code but I haven't found out why it works yet.
You don't need to use call() in this situation. call() is used when you need to set the value of this in a function. If you aren't doing that, just call the function like you would any other function. For example:
function Example(callback) {
// call the function passed in
callback("Hello")
// this also works, but there's no benefit here
// because the callback doesn't care about `this`
// callback.call(null, "Hello")
}
// pass a callback function to Example
Example(function(text) {
console.log(text);
})
You would use call in situations where the callback function needs a value for this. For example:
function Example(callback) {
let person = {name: "Mark"}
// set this in the callback to the person object
// and the execute it with the argument "Howdy"
callback.call(person, "Howdy")
}
Example(function(greeting) {
// the callback function depends on having this.name defined
console.log(greeting, this.name);
})
This looks pointless at the first glance, however, there might be valid reasons for this syntax, for example:
the callback relies explicitly on this being null and not some global default
the callback is not necessarily a function, it can be a "function-alike" object that provides a .call method
callback.call(... is used consistently through the application, no matter if this is needed or not
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.
This is a simple question. Here is my code:
$(document).ready( function () {
func1( "foo", callback);
function callback(param){
alert(param+" is my name");
}
function func1(name, cb) {
cb(name); // alerts "foo is my name"
callback("bar"); // alerts "bar is my name"
}
});
I want to know:
Which one of the function calls inside func1 is the correct callback and why?
Or are they both correct?
Isn't callback("bar"); a normal function call?
Callbacks are meant to let a caller specify what a function should do at some defined point in that function's execution. The function being called shouldn't know the name of that callback function ahead of time. So they'll often be passed to a function as an argument and the function that's supposed to call the callback should just invoke that argument.
When you call callback("bar") in func1, you're totally missing the point of callbacks. You may be invoking the function that you happen to use as a callback, but the point of callbacks is that func1 isn't supposed to know about that. It's just supposed to call the function that's been passed in as an argument (cb). When I'm calling func1 I should be able to pass a completely different callback function and func1 should just call that function without knowing what its name is (it may not even have one!).
The "correct" way is cb(name).
callback("bar"); is directly invoking the callback function where as cb(name); calls the reference passed to the func1,
cb(name); seems to be the correct way here.
First one. Function calls another one which has been pased as a parameter.
It seems like most jquery methods follow this this form for callbacks:
$(SUBJECT).method(function() {
//do stuff
}, /*callback here*/ function(){
//do stuff
});
like for instance
$(foo).click(function() {
$(bar).fadeIn(300, function(){
//call back here
});
});
fiddle
How can I get this function to pass by reference with this code?
var Class = function() {
var callback1;
var callback2;
function buildStuff(data, callback) {
element.onclick = function() {
doStuff(callback);
};
}
function doStuff(callback) {
callback();
}
return {
"setCallback1":function(fn) {
callback1 = fn;
},
"setCallback2":function(fn) {
callback2 = fn;
},
//may rebuild with different data, but same callback
"buildFoo":function(data) {
buildStuff(data, callback1);
},
//may rebuild with different data, but same callback
"buildBar":function(data) {
buildStuff(data, callback2);
}
};
}
function main() {
var object = Class();
object.setCallback1(function() {
//do stuff
});
object.setCallback2(function() {
//do something else
});
}
When you actually click on the element, callback is undefined. I would expect it to be the anonymous function I set it to with the setCallback function because the user click occurs after I call the setCallback function.
Thanks!
EDIT: Thanks for the input. I should have mentioned I need to be able to dynamically set what callback equals. So, I can't just eliminate the callback parameter from buildStuff.
EDIT2: Very sorry for the confusion; I realize my example was a bit too out of context to show what I am doing. buildStuff is actually a private member function (using the module pattern) that is called repeatedly. Depending on what is being built, it needs a different callback. The callback is actually set outside of the class (well, module pattern class), so it has to be dynamic. I've updated my code, and again, sorry for the bad example.
The click handler you create in buildStuff creates a closure over the local variables. You pass callback to your buildStuff function, but at the time you pass it, it's undefined. As this shadows the other callback variable, you always see this value of undefined, rather than the state of the other callback variable.
Instead, don't pass a parameter to buildStuff, and the closure will be created, and will capture the callback variable you want.
function buildStuff() {
element.onclick = function() {
doStuff(callback);
};
}
Imagine this;
Your global variable callback points to a value (in this case undefined).
When you buildStuff in main(), you pass the value pointed to by callback (undefined) as a parameter to buildStuff
Your click handler creates a closure over local variables + other variables in scope (note that the local callback shadows the global callback). callback in your event handler is now undefined.
You then setCallback. setCallback changes the value the global callback variable points to using the = operator. The global callback and local callback now point to different values, which is why you don't see the callback in the event handler update.
What you want to do in this situation is to change the value pointed to by callback, so other variables pointing there also update, but JavaScript doesn't let you do this.
Yes, but you've already called buildStuff before setCallback.
The contents of callback at the time (undefined) will be used.
If you want to call buildStuff with different callbacks, just do that, and eliminate the redundant setCallback:
function buildStuff(callback) {
element.onclick = function() {
doStuff(callback);
};
}
function doStuff(callback) {
callback();
}
function main() {
buildStuff(
function() {
//do something
}
);
}