Skip to content Skip to sidebar Skip to footer

Trying To Pass In A Callback Function Fails

I am trying to create some functionality when a user clicks on an element on the webpage. The callback function executes as soon as the page is executed. It is only supposed to exe

Solution 1:

That isn't actually passing the function, but instead it is evaluating the function and passing the result as the callback parameter (in this case, undefined).

Try this instead

<script>functionprintThis(msg) {
    console.log(msg);
  }
  $("#clickMe").one('click', function() {
     printThis("Hello All");
  });
</script>

Solution 2:

Don't invoke the callback. Pass an anonymous callback function that invokes the function you want.

functionprintThis(msg) {
    console.log(msg);
}

$("#clickMe").one('click', function() { printThis("Hello All") });

Solution 3:

one method takes a callback as the second parameter. printThis("Hello All") will actually call the method there itself so on click of clickMe nothing will happen as there is no handler attached. Try this

functionprintThis(msg) {
    console.log(msg);
}

$("#clickMe").one('click', function() { printThis("Hello All") });

Solution 4:

The answer already posted is right:

$("#clickMe").one('click', function() { printThis("Hello All") });

This is known as a closure: https://developer.mozilla.org/en/JavaScript/Guide/Closures A closure is a function, often declared as an inline/anonymous block of code, that delays the execution of your function and stores the value of that "Hello All" argument that you want to pass in.

jQuery will store this "function() {...}" code block as an event handler, and then later when the #clickMe element is clicked, that code block will be executed, which in turn will call the printThis function.

You will find yourself using this pattern quite often with jQuery.

Solution 5:

Post a Comment for "Trying To Pass In A Callback Function Fails"