React JS: calling event handlers - javascript

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

Related

passing event handler as reference

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

Function Call as parameter of another function on Javascript

First of all, i need this to be capabe to run on I.E. 8 at least (work requirements) and i can't use jQuery or another library to reach this.
The "issue" is that there's a function onKeyDown with a preventDefault and a function triggered onChange, which never (or randomly) executes due to prevendefault (long to explain more). I't could be solved as i'm reading onChange value and i'm setting it as onPlay, then i delete onchange attribute and the behaviour is to check if changes exists when onBlur and i'm triggering onplay event from this control function if there are changes.
Well, onPlay event (and other multimedia events) are only supported on IE 9 and up, so i need to find a way to pass through this. i can't use other events as they could be used on somewhere and could cause issues.
My idea was to send onChange value as function parameter to control function and execute it instead on triggering onplay event, but is causing me headache, it simply does nothing when i'm trying to do it.
//this is a resume of the function:
function foo(obj){
var funcioChange = toString(obj.getAttribute('onChange'));
obj.setAttribute('onBlur', 'checkChanges("'+obj.getAttribute("id")+', '+ funcioChange+'")');
obj.removeAttribute('onChange', 0);
}
When onBlur:
function checkChanges(idinput, functOnChange){
if (foo){
functOnChange;
//another things
}
}
If the function doesn't have parameter/s or you need to put it/them later in another function, you can do
foo = yourFunction;
function2 (foo){
foo(param1, param2);
}
if you have to send the params with the function call:
foo = "yourFunction(param1, param2)";
function2 (foo){
foo;
}

How to pass extra parameter to event handling callback?

I have a button on which I want to attach an event listener. I also need to pass a extra parameter url to this function. I read about apply and I'm doing the following:
$('#list-button').on('click',postListing.apply([url]));
My problem is that as soon as this script is loaded postListing is called. I am not calling the function anywhere else. I need it to be called only on click.
The difference between bind and call/apply is that bind doesn't call the function immediately much like it loads the data with the variable when needed
You can reformat your code so it looks like this
$('#list-button').on('click', postListing.bind(this, url));
Found a way. It can be done using a closure:
var postListing = function(event, url){
return function(){
//Main functionality wrapped here
};
};
And the event listener setting remains the same:
$('#list-button').on('click',postListing.apply([url]));

How to pass the event argument of jQuery .click() to a non-anonymous function

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/

Confused about a couple of things when writing Event Handlers

So I'm trying to gain advance Javascript skills. So I'm doing a practical JS tutorial on Lynda.com. Chapter 3 is on EventHandlers and I'm a little confused (Note: I've deleted the code that makes the script work in all browsers). I've rewatched the videos and that hasn't been helpful at all.
What is the e referring to? I don't have a variable at all named e or anything else that I can see.
What is false referring to? Is it the same as return false since I'm dealing with a link?
function clickLink(e) {
alert("You Clicked the Link");
}
function linkClicked(e) {
addEventHandler(document.getElementById("clickLink"), "click", clickLink, false);
}
addEventHandler(window, "load", linkClicked, false);
The e just refers to the event that has taken place, you can change it to anything you want. It just passes the event around to the various functions etc. that need to use it.
The false simply means that the event is not 'consumed', i.e. it can be used by other handlers if you have multiple handlers for the same event. So, yes, it is effectively the same as return false. (see my link below about bubbling)
See here for more on consuming events and bubbling.
First of all e is just an argument that you will receive in the function. You could also write something like this:
function evtHandler(){
console.log(arguments[0]);
}
Where arguments[0] is your given e. The handler function is called when the event is fired. Usually in the e argument you have an object with some info about how fire the event.
When you add an event handler, the last argument on that function is a boolean one, which indicates if the handle should or shouldn't bubble in the event handler's chain. It is not as you would return false, but if the event would be handled by other handlers also. If you want to return false or ignore the previous default handling you could call the preventDefault function inside the evtHandler.
P.S. Take care with event handlers because there are some problems with cross-browser compatibility;
if you are talking about e in clickLink(e), then i can say you can declare whatever parameter you want in a javascript function prototype,but when calling it you can provide parameters optionaly.and here in clickLink(e) you can pass a parameter for e or you can simply ignore it.and about the false in addEventHandler check this documentation also check this SO question .
for example if function FO is defined so:
function FO(e){
//function body here
}
then you can call it like this :
FO();
OR
FO("BAR");

Categories