I've just learned to use callback functions, and this is the way I'm using them:
//click event function
function elementClick(element, callback) {
element.addEventListener("click", function(){
callback();
});
}
This allows me to simply trigger a function when an element is clicked like so:
elementClick(modalSkipBtn, loadNewCombination);
Is this the correct way to be using the callback function? My code is working fine - I am just wondering if this is a appropriate use for this function.
Yes the implementation is correct. You could also simple write element.addEventListener("click",callback);
Or if your function is loadNewCombination()
element.addEventListener("click",loadNewCombination);
You can simply use element.addEventListener("click", callback)
. The reason is that you can pass the function without invoking it (ie adding ()
after its name). addEventListener
accepts a second argument which is a function in the same exact way your elementClick
accepts it. and call it within.
You can do element.addEventListener("click", callback);
instead, it's easier. Use you method only when your callback needs a parameter. Example:
element.addEventListener("click", function(){
callback(i);
});
function callback(i) {
return i * 2
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.