onChange in react.js - javascript

I am new to react.js. I am little bit confused about onChange event in react.js. Why we are not using brackets while handling the event through onChange event?
<input
type="text"
onChange={this.handleChange()}
/>
Normally when we handle the event through JavaScript we would write like this
<input type="text" onclick="handleChange()"/>

If you mean why we need to do onChange={this.handleChange} instead of onChange={this.handleChange()} - the first one makes gives a reference of handleChange to the onChange. The second one immediately (as it is interpreted) runs the handleChange function and the return value of that is saved as a referece for the onChange.
Think about it like this
onClick={alert(123)} // this runs alert immediately
onClick={() => alert(1)} // makes a new function will run when clicked
onClick={alert} // this runs alert when clicked
If you need the event object of in your event handler, think about where you would get that from; you need to get it as a function parameter and for that you need a new function or reference:
onClick={console.log} // logs the event object
onClick={(event) => console.log(event)} // also logs the event
onClick={console.log(event)} // runs immediately, event doesn't exist then
When you have an inline event handler like onclick="handleChange()" your browser actually evaluates the string "handleChange()" as you press. Like with the eval() function. Try doing eval("alert()") in dev tools and do note that there "alert()" is a string
PS. Welcome to SO! Please check the formatting of your question next time :)

Related

Enqueuing function to run after all events on current form are handled

I have a form with a formdata event handler that updates a field of the FormData if a certain state is found in the DOM. After the form submission, the DOM needs to be changed, but the formdata event handler should still observe the old state. Currently, I achieve this by using setTimeout(() => {/*...*/}, 0) in a submit event handler on the same form, because this will enqueue the function to run later - hopefully, after the formdata event is handled. My question is: Is this behavior guaranteed, and if not, is there a specification-backed way to accomplish this behavior?
In the specification of event loops, the first step for choosing what work to do next is described as:
Let taskQueue be one of the event loop's task queues, chosen in an implementation-defined manner [...]
The oldest task from this chosen queue is then run later on. This would mean, that if functions scheduled with setTimeout are in the same task queue as the event handlers and if the formdata event handler is scheduled before the submit handler is actually run, I would definitely be safe - I cannot find any evidence for that though. From the documentation of the formdata event ("fires after the entry list representing the form's data is constructed") and the fact, that the formdata handler is run after the submit handler, I would even assume the contrary to be true - but that is not what I observed with the approach described above.
Your understanding is quite correct, and you are right that setTimeout(fn, 0) may not always fire after a "related" event: it is indeed very possible that these events are fired from two different tasks, very unlikely they'll use the timer task sources, and you correctly identified the bit that would make the event loop "possibly" select a task from an other task source.
However in this exact case, you are safe.
The submit event and the formdata one are fired from the same "task"*.
If you look at the form submit algorithm, you can see that the submit event is directly fired at step 6.5, instead of being wrapped in a task that would get queued like it's often the case.
Let shouldContinue be the result of firing an event named submit at form [...]
Then in the same algorithm, without any in parallel or anything implying asynchronicity, we have the step 8 that says
Let entry list be the result of constructing the entry list with form, submitter, and encoding.
And in this constructing the entry list algorithm, at the step 7, we have the call to
Fire an event named formdata at form [...]
once again without any asynchronicity allowed.
So we can be sure that these events will fire without anything else in between (apart microtasks), and that your timer callback from the submit event will fire after the formdata callback, even two requestAnimationFrame callbacks scheduled in the same frame (that are also "synchronous" for the event loop) won't be able to interleave there:
document.forms[0].addEventListener("submit", e => {
console.log("submit");
});
document.forms[0].addEventListener("formdata", e => {
console.log("formdata");
});
requestAnimationFrame(() => {
console.log("rAF 1");
document.forms[0].querySelector("button").click();
});
requestAnimationFrame(() => {
console.log("rAF 2");
});
<form target="target">
<input value="foo" name="bar">
<button>
submit
</button>
</form>
<iframe name="target"></iframe>
*Technically it does not even need to be from a task per se, you can very well force these events to fire from a microtask or a resize event callback etc.)

How to remove event listener or emitter listeners in React Native

I am trying to remove an event listener. The old way is deprecated. We are told to use .remove(). I am not sure how to refactor my code to do so. I am using a class component.
Can you provide an example of how to remove event listener. Currently my event listener is inside of another function. I have it that way as I may need to create another event listener every time the button is press and I need to remove the listener after the function runs.
startProcess = (result) => {
// stuff for running process
console.log("your function is running its process");
//deprecated but easy way to remove the event listener below
// eventEmitter.removeListener('PreparePaywallFinished', onPreparePaywallFinished);
//new way to remove event listen use remove() method on the EventSubscription returned by addEventListener()
this.subscribeStartProcess.remove;
};
handleBtnPress = () => {
// the listener
eventEmitter.addListener("onMidiStart", this.startProcess);
// emitter
NativeModules.midiBridgeStart(true, 2);
};
render(){
return <Button title='press' onPress={()=> handleBtnPress() />
}
You can use
window.removeEventListener('onMidiStart', handleonMidiStart);
the second argument in the removeEventListener is a variable to identify which event listed is being removed . A detailed description is being given here enter link description here

I do not understand Using addEventListener javascript

Hello am really stuck on getting more information on addEventListener can someone please point me to the right direction, I will like to get some more information on what type of argument can be passed into a function parameter is their a website or a link that i can view for all available javascript function and tell me what a parameter takes. in the below eg eventOne.addEventListener() is called however this code taken else where and am unsure why the argument are passed into the parameter and why a function with no name given
var eventOne = document.querySelector("h1")
eventOne.addEventListener("mouseover", function () {
eventOne.textContent = 'mouse over'
})
Anytime you interact with a browser window an event fires. The addEventListener method listens for any event you tell it to. The idea behind this method is basically you telling your browser: Hey, when this thing happens to this element, please execute this code.
Here is a link to all the events you can listen for.
The addEventListener method takes two arguments:
The first argument is the event you want to listen for. The code example listening for a mouseover event. According to the events reference this event fires off when a pointing device is moved onto the element that has the listener attached or onto one of its children.
The second argument is a callback function. This is the function that will execute when that event fires off on that DOM element.
Here is a more common example:
const heading = document.querySelector('h1');
heading.addEventListener('click', function () {
console.log("I have clicked the h1 tag")
})
You can use this tactic to implement logic into your code when certain events happen. It is very powerful.
Let me briefly try to explain ... before I ask you to simply "google it" and start reading.
"When things happen," such as when the mouse-pointer moves over something, an "event" is sent to the thing that it happened to ... and it "bubbles up" from there. Of course you cannot predict when these events will happen, but you can "listen" for them.
When an event is "listened to," what happens is that the specified function() will be called at that time, with various optional parameters. (Furthermore, there's some additional "JavaScript voodoo magic" that can happen -- Google the term, "closure.")
So, when the mouse passes over this object, the specified function will be called at that time, and it will change the textContent as shown.
Now ... "off to Google-land!" There are literally thousands of articles on the Internet which explain this much better than I did. (May I recommend: "w3schools.com." There, you can actually "try things out!")

How does "keydown" know to automatically pass an argument to a Function?

The following code works perfect.
If the ESC key is pressed function closeModal fires.
window.addEventListener("keydown", function(e) { if (e.keyCode == "27") { closeModal(); }} );
I must be missing an important piece of knowledge because from a technical standpoint I'm not sure how/why keydown knows to create and then send the e argument to the function. How does keydown know to send e anywhere at all?
As a comparison in this code that uses click no argument is sent or asked for. I know the function isn't written to accept an argument but I don't think click creates or sends an argument anyway. And if it did how would it know to get to the function sitting next to it? Maybe I'm wrong about all of this.
document.getElementById("portfolio-large").addEventListener("click", closeModal);
Everything is described here and here
Basically you are attaching callback function which is then called upon event with event itself as an argument.
You are wrong about click listener - it also receives an event argument.
The event is created by the browser.
So when you attach a listener to the window object and that event fires, the browser creates the event and passes it to your function. It will work with any event driven action including click.
https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener

How to remove the handler in javascript

I'm adding some document to addhandler, where this script will execute on each time on ajax call.
But on the ajax result how can I remove the handler, where i tried using removeHandler but for the first time its getting affected.
Is any method to check whether the event is alive kill it.
If you want to remove an event handler with Javascript, you need to unsubscribe it this way:
document.getElementById("yourelement").removeEventListener("yourEvent", yourFunction);

Categories