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

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

Related

onChange in react.js

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 :)

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!")

Why can't eventDragStop not edit the event in the callback? (FullCalendar v4)

I'm using fullcalendar (the v4 alpha) to arrange events.
I have an eventDragStop callback that I'm trying to use to set an extendedProp for an event, marking that the event has been altered.
eventDragStop: function (info) {
calendar.getEventById(info.event.id).setExtendedProp("extra2", true)
}
Using the code above, it doesn't work. If I alert(info.event.id), I can see that the correct ID is being called for the event that has been dragged, and get no errors.
If I have three events on the calendar, with IDs: 1, 2, 3, and use the following code:
eventDragStop: function (info) {
calendar.getEventById(1).setExtendedProp("extra2", true)
}
So, explicitly stating to change ID number 1, rather than the event in the callback.
If I drag event number 1, this doesn't work either. However, if I drag event 2 or 3, it will work and change event 1.
Vice versa, any event I explicitly state, it will be able to change that event, providing that was not also the event that triggered the eventDragStop callback.
Can anyone tell me why this is?
https://fullcalendar.io/docs/v4/eventDragStop says (of itself as a callback)
"It is triggered before the event’s information has been modified"
So I think what is happening here is that fullCalendar effectively overwrites any change you make to the event data during this callback.
I think this is because the event object maybe gets replaced with a new version (constructed based on its final resting place) some time after this callback runs.
I haven't verified this by looking at the source code but it's a logical explanation for the issue you're seeing, and it also makes some sense that the event object would get updated (with new dates/times etc) after dragging is complete, and that this might in fact involve a full refresh of the object data at that time.
Anyway, that's why when dragging event 1 you then fail to persist any updates to event 1's other data, but when dragging event 2 or 3 you are able to persist the changes to event 1 - because in that instance event 1's data is not being replaced at a later time as a result of the dragging being completed.
Instead of using eventDragStop, you should modify the event during eventDrop (https://fullcalendar.io/docs/v4/eventDrop) instead. This callback occurs after fullCalendar has completely finished processing the dragging/dropping and updated the event times etc. Therefore any further changes you make to the event data I would expect should be preserved.

Bug or i do a mistake with inboxsdk "presending" event

When i use the inboxSDK with the newGmail I face an issue that the "event" did not get the composeView like the other events.
sdk.Compose.registerComposeViewHandler(function (composeView) {
composeView.on("presending", function (event) {
// Only get event.cancel();
});
}
Did i do something wrong or it's a bug with the new Gmail UI ?
As of the documentation the presending callbacks event object only has the cancel method attached. And actually that is no problem at all since you already have the composeView availbale from the registerComposeViewHandlers scope. Just access that composeView object.
sdk.Compose.registerComposeViewHandler(function (composeView ) {
composeView.on("presending", function (event) {
console.log(composeView);
});
}
If the presending event triggers you can just use event.cancel() to stop the sending, do whatever you wanna do on the composeView like you would for example in the registerComposeViewHandler callback and when you're done do composeView.send() to finally send the email. Just make sure to have a condition for the cancel event so you actually be able to send at one point and not get stuck in the presend event forever.

Handling JavaScript events not handled by other elements

I am writing a script where I would like to handle mouse events only if they have not been handled by any other element before.
I can attach an event listener to the document object, but it will receive all events regardless of whether they have been already handled.
I have no control over the elements in the HTML page so I cannot manually stopPropagation() when the event is handled.
Any ideas?
From this article here.
It seems its not yet possible to do this.
Which event handlers are registered?
One problem of the current implementation of W3C’s event registration
model is that you can’t find out if any event handlers are already
registered to an element. In the traditional model you could do:
alert(element.onclick)
and you see the function that’s registered to
it, or undefined if nothing is registered. Only in its very recent DOM
Level 3 Events W3C adds an
eventListenerList
to store a list of event
handlers that are currently registered on an element. This
functionality is not yet supported by any browser, it’s too new.
However, the problem has been addressed.
Fortunately
removeEventListener()
doesn’t give any errors if the event
listener you want to remove has not been added to the element, so when
in doubt you can always use removeEventListener().
So, you can accomplish something like you want under a certain set of circumstances. Specifically, if
You can load your own custom JavaScript before the original
You know which elements you are listening for others to throw events on
Effectively, what you do is replace the original addEventListener method on the target element with a custom one that intercepts the call, does some special processing, and then lets it continue per normal. This 'special processing' is a new function that wraps the original callback, and marks the event arguments with some state to let you know someone else handeled the event already. Here is a proof of concept (with a jsFiddle)
Target HTML:
<div id='asdf'>asdf</div>​
JavaScript:
var target = document.getElementById('asdf');
var original = target.addEventListener;
var updated = function(){
// Grab the original callback, so we can use it in our wrapper
var originalFunc = arguments[1];
// Create new function for the callback, that lets us set a state letting us know it has been handled by someone
// Finish the callback by executing the original callback
var newFunc = function(e){
console.log('haha, intercepted you');
e.intercepted = true;
originalFunc.call(this, e);
};
// Set the new function in place in the original arguments 'array'
arguments[1] = newFunc;
// Perform the standard addEventListener logic with our new wrapper function
original.apply(this, arguments);
};
// Set the addEventListener on our target to our modified version
target.addEventListener = updated;
// Standard event handling
target.addEventListener('click', function(e){
console.log('original click');
console.log('intercepted?', e.intercepted);
})

Categories