this is an exercise from codecademy. Why does it require to pass the event handler as a reference? why i can't type onClick={goBack()} instead of onClick={goBack}
const goBack = () => {
setQuestionIndex(prevQuestionIndex => prevQuestionIndex - 1);
}
....
<button onClick={goBack}>
Go Back
</button>
When you are using onClick={goBack()} then you are invoking/calling the function goBack and the result of goBack invocation get passed to onClick
Live Demo
But If you are using as onClick={goBack}, then In this case you are passing a reference to the onClick which means when user click on the button then It will automatically invoke the function. You don't have to invoke the function yourself.
1) Let say consider function with value
<button onClick={fun()}> button with function reference</button>
If you are passing value to a function then first of all it will produces a warning in the console as:
Warning:
Expected `onClick` listener to be a function, instead got a value of `string` type.
and when you invoke it then it will throw error as
Error
Expected `onClick` listener to be a function, instead got a value of `string` type.
2) If you are using as
<button onClick={fun}> button with function reference</button>
then function fun will be passed as a prop and when use click on the function then this function fun will get invoked automatically
goBack is a reference to a function, goBack() calls that function and returns the result.
In the case of the click handler for a button, of course, you want the function to run when the button is clicked, not when the button is rendered. That's why you need to pass the function, rather than calling it (on render) and passing its result.
If you pass in the function call instead of the reference, it will call the function as soon as your component renders, the reference is bound to the click handler, hence when the specific event triggers, it will callout to the reference.
Here is a snippet to see this,
Sandbox
Related
I have started working in React recently. I noticed one behaviour like when I am trying to call my event handle with the same component like this
onClick={someEventHandler} it is triggering but when I try to do the same same like this onClick={()=> someEventHandler} it doesn't work.
I noticed that when I need to pass any arguments and calling the function like onClick={()=>someEventHandler(id)} it is working fine.
can some one explain me the logic/theory behind this?
The onClick event handler needs a function to be passed to it. Whenn the event is triggered, it calls the handler function passed to it.
In the first case it works because you pass someEventHandler to onClick which is invoked when event is fired. An invocation to the function is like someEventHandler()
Now in the second case,
onClick={()=>someEventHandler}
the function passed to onClick is ()=>someEventHandler which can be elaborated further as ()=> { return someEventHandler; }
Now if you notice above you are returning a function from the onClick event handler. The returned function is now never invoked and hence you see the above behavior
It works in the last case like onClick={()=>someEventHandler(id)}, because when the event handler is invoked, it invoked someEventHandler with id too.
However you do not need to pass id to invoke it, you can simply use it like onClick={()=>someEventHandler()} and it work, provided you don't need id as a parameter in someEventHandler.
Another thing to note when you are using function like onClick={()=>someEventHandler()} instead of onClick={someEventHandler} is that your someEventHandler will not be invoked with any arguments. If you want the event to be passed as argument to someEventHandler, you need tto explicitly pass it like
onClick={(e)=>someEventHandler(e)}
onClick={someEventHandler} will trigger the handler as soon as your component gets loaded/rendered on the screen but by adding an arrow function before the handler like this - onClick={()=> someEventHandler} will make sure not to trigger the component before you click on it
I want to load a function on click event using $.proxy.
If i load the function using the below click event then everything works fine.
click event which is working
$('element').click($.proxy(this.doProcess, this));
click event which is not working
$('element').click(function(){
// Perform other things
$.proxy(this.doProcess, this);
});
As you can see that i want to perform other things on the click event before loading the function. Can you please help me figure out why it is not loading if i use ".click(function()..." instead of simply '.click()..'
Because in the first snippet the click function calls the returned function. In the second snippet you are binding the current this value to the function, but you don't call the returned function. You can use the invocation operator (()) for calling the function:
$.proxy(this.doProcess, this)();
Note that this in the context of the anonymous function (which is the current event handler) doesn't refer to the this keyword's value of the outer context, you can cache the value:
var that = this;
$('element').click(function() {
// Perform other things
$.proxy(that.doProcess, this)(/* arguments go here */);
// | |
// | ----- refers to the clicked element
// ----- reference of the outer context's `this` value
});
What is the proper way to accomplish the following:
$("#btn").click(function1);
Calling the function:
function function1 (event) {
event.preventDefault();
}
This seems to work, however I don't understand how function1 understands what the event argument is referring to without it being passed in. Wouldn't a listener set up like this make more sense:
$("#btn").click(function1(event));
Here is a fiddle.
The .click() function in jQuery except as first parameter a function. In Javascript function are value, as well as a primitive value or an object. Functions are first-class citizens.
If you use function1(event) as a parameter, the function will be executed, because this is the semantic of the brachet after the function name. So the .click() jQuery function will receive the output of the function, which is not the expected type.
Passing the function name as a parameter means that you are passing the function (actually, a reference to the function), not the result of the function invocation. And the function will be called when the click event will be triggered. The function in this case is called "callback".
Callbacks are very importants in Javascript, since the event-driven behaviour is the main reason for using a client-side scripting.
The concept behind the callback system is
//the click function
function doSomething(callback){
//in your case the event is the argument that jQuery will prepare for you
var argument = produceTheArgument();
//doSomething is in charge to invoke the function, passing the argument
callback(argument);
}
//your function
function myCallback(argument){
//your function will consume the argument
}
//my callback is passed as a reference, not invoked
doSomething(myCallback);
you are subscribing to event and passing a reference to the function inside click listener - the jQuery event processor will just call your function in jQuery's context and will pass all parameters to it.
In your first example function1 knows that the event variable is, because JavaScript (and subsequently jQuery) passes the event information as a parameter.
This is the nature of JavaScript, not just jQuery. Consider the following:
document.getElementById('btn').addEventListener('click', function1, false);
function function1(e)
{
console.log(e);
}
JavaScript automatically calls function1 when #btn is clicked, and it automatically adds the event information as the first parameter. jQuery simply passes this information into its own methods as well, so that you have access to it.
According to jQuery's documentation:
The click event is sent to an element when the mouse pointer is over the element, and the mouse button is pressed and released. Any HTML element can receive this event.
Reference: http://api.jquery.com/click/
In traditional event registration model:
function foo(e){console.log(e.type)}
document.getElementById("#id").onclick=foo;//registered event handler
But in inline event registration model:
<a href="#" onclick=foo(event)>clck</a>
console.log(a.click)===function click(){foo(event)}
Can't event object be used directly within the function foo rather than pass as a function argument.Since event object being used within the click function is not passed by the browser we are manually passing it.Why passing event object within the event handler function dont work?
Since event object being used within the click function is not passed by the browser we are manually passing it.
That's not correct. The browser (at least W3C compatible browser) pass the event object to the event handler.
The equivalent to
onclick="foo()"
is
elem.onclick = function(event) {
foo();
};
The browser creates a function with event as first parameter and uses the value of the attribute as body of the function.
You have to pass the event object explicitly to foo because that's how JavaScript functions work. If you call a function inside another function, the outer function's parameters are not automatically passed to the inner function (that would be really confusing IMO).
Simpler example:
function foo(a) {
bar();
}
function bar(a) {
alert(a); // will show `undefined`
}
foo(42);
Can I pass an additional parameter to this function?
$("#foold").click( function(e) {
// CODE
};
For example, I need to pass some X value to this function. Can I write something like this:
Foo
to pass value in this function through e or some other way?
Here, e is an event object, as defined here: http://api.jquery.com/category/events/event-object/
Yes you can pass data to the handler, using this form for the click function:
.click( [eventData], handler(eventObject) )
eventData A map of data that will be passed to the event handler.
handler(eventObject) A function to execute each time the event is triggered.
It will be accessible as e.data in the handler.
In this link you can see how to pass params to the JQuery click function jQuery's .click - pass parameters to user function
Basically
It allows you to pass a data map to the event object that
automatically gets fed back to the event handler function by jQuery as
the first parameter.