Это видео недоступно.
Сожалеем об этом.
Creating and Dispatching Custom JS Events
HTML-код
- Опубликовано: 20 окт 2017
- Did you know that, even though the browser comes with a long list of built-in events, you can create your own custom events and have them dispatched whenever you want?
Code GIST: gist.github.co...
Good job, Steve! Custom events have been bugging me lately and no amount of reading could get the job done for me. RUclips also seems to lack good videos on the topic and I dare to say yours is right on the spot. Thanks!
Maxim Kehayov thank you!
Very true.
Yes, yes, YES! "Crystal clear" is an understatement regarding the explanation and the presentation...
Great tutorial, Steve...thank you!
There are literally no clearer videos on the internet on how to learn JavaScript. When I want to learn something to do with JavaScript and I want to learn that part in one video without messing about and having to look up other things or watch it again and again, your channel is the first place I look.
Very helpful, I tried reading about custom events and couldn't understand a thing, because all the explanations I found online were rushed, more like cheat sheets than actual explanations for people to learn from, but this video explained them very well and simple.
Perfect clarity! Thanks Mate.
Perfect explanation. Thank you for the video.
Good explanation 👍👍👍
Thanks, Steve! This is what I was looking for. Perfect!
Can you go into any kind of detail on a situation where this would be better than just calling the 'wasBorn' function within addParagraph? I understand that this was meant to be an example video, but I haven't found a situation where it was better to create a custom event than just call a function and I wonder if it's because I'm missing something.
Creating an event means you can make an element wait for your event instead of one of the built-in DOM Events.
When you are creating your own Objects and need them to listen for events then you can't just add a click listener. I use DOM elements in the example because it is a common frame of reference for people.
Here is a real world example of a custom event - swipeleft. There is NO swipeleft event in JavaScript. A swipe is a combination of a touchstart, followed by movement in a specific direction beyond a minimum distance within a limited amount of time, followed by a touchend event. I can create my own swipeleft custom event that people can add to an element on their page. The code inside my event can add the touchstart and touchend events to the same object and then listen for all those conditions.
The person using my JavaScript will only have to add a swipeleft event and not worry about all the logic behind the scenes.
That's a great example. Thank you!
What do you mean by "the code inside the event"?
Perfect tutorial on custom event...
I believe modern browsers will automatically GC event listeners on a removed element as long as it's not referenced anywhere.
GC has improved over the years but it is the not referenced part that is most challenging for junior developers.
Thanks for the tutorial Steve! Have been struggling with the idea of custom events lately and I think this video(as well as the series) definitely helped me gain better understanding into how events work! Just want to make sure I got it right: so the code before you call dispatchEvent is the logic of the event correct? i.e. the chunk of code before dispatchEvent determines the logic of my custom event, and when these happen, my event meets its criteria and can be triggered if there are elements listening to it, correct? Thanks in advance for your answer!
The two main parts of all this are:
1. element.addEventListener( eventType, functionName)
1. element.dispatchEvent( newEvent )
The addEventListener method tells the element to listen for an event of type `eventType`. When that happens the function `functionName` will run.
The dispatchEvent method tells the element to pretend that an event of the type defined in your `newEvent` object just happened to the element.
Everything else is just setting things up to demonstrate an example. dispatchEvent can be used to trigger ANY kind of event - click, mouseover, load, or something custom like `born`.
You can call dispatchEvent on any element on your page.
Thanks for the thorough reply! Yeah, I understand what you said. So my main question before was just on how to define the "prerequisite" of the custom event I'm gonna build. By that I mean say I have a custom event, and only when condition A, B, C are all met does the event got triggered. So now I think what I can do is write a function, in which I define all the things that need to happen (using Leap Motion API, so say my index finger coordinates need to be on top of the application), and then dispatch my custom event, like fingerHover. This way I can have my elements listen to the custom event. Does it sound like the right way to do it?
The eventListener functions are triggered any time that the event happens. If you want to filter conditions on the event then you will probably have to do that inside the function that happens when you dispatch the event. There is no way to add conditions with the addEventListener( ) method.
So you either wrap the dispatchEvent call inside some program logic, OR if the conditions you are checking are part of the event then you need to do it inside the function that was called through the addEventListener method.
Thanks a lot Steve! Got it working!
Great, very clear 👌
awesome thanks
Hey Steve! Thanks for the video. I have a doubt in exactly 7:15 when you are dispatching the event. Do we use dispatch event to call the function when a custom event occurs because that is what is done in the previous addEventListener() method. When a custom event occurs, the addEventListener() listens to it and calls the related function. Please let me know why we use dispatch event
dispatch event is used to simulate an event happening. Let's say that you have two buttons for the user to click. Each button being clicked calls one function. With dispatch event you can have the first function run and pretend that the second button was clicked too.
When you create your own custom events then dispatch event lets you trigger those custom events to call functions.
@@SteveGriffith-Prof3ssorSt3v3 - Thanks! I am kind of getting it now. Also , I wanted to clarify if the addEventListener() can be defined anywhere because here the addEventListener() for "Died" event is defined in the addParagraph() method. Shouldn't it be defined in the removeParagraph() method() and dispatched there itself. Thanks!
What is the difference between appendChild, insertAdjacentHTML
i dont no
but
i think insertAdjacentHTML is cleaner
is it?
insertAdjacentHTML lets you target a specific location relative to some other element.
99% of the time you will be adding the new content from an array or as the last item in a list. The best choice for this is the newer append( ) instead of appendChild( ).
@@SteveGriffith-Prof3ssorSt3v3 thank you you are nice teacher
after js
i work with vue & nuxt-js & es6 i scarred that i forget vanilla js
please say me what shoud i do?
thank you.
@@mohammadaliafrasiaby2347 es6 is vanilla js. Practice is the only thing you can do.
Awesome
12:04 I'd also add this event listeners to the parent, not children, as they get created and destroyed dynamically... handling events for children is more troublesome.
Thanks, Steve!
Why not use {once:true} option to remove listener automatically
That was not broadly supported when I made this video
@steve Griffith, can i also ask something ?
You just did.
I tried to do a dispatchEvent on a button with disabled state in ie11 but it won't fire it. Help me please :(
With this HTML
Click me
and this script
document.addEventListener('DOMContentLoaded', () => {
let btn = document.getElementById('btn');
btn.disabled = true;
btn.addEventListener('click', (ev) => {
console.log('button clicked');
});
let ev = new MouseEvent('click');
btn.dispatchEvent(ev);
});
you will never see the console message.
If you comment out the btn.disabled = true; line and then you will.
If the button is disabled then it does not report the click event.
good job
after js
how long does it take to learn node .js???
NodeJS is JS. Core JS is the same on the browser and in node. They just have extra things added on. Browser has the DOM and browser specific things like localstorage etc.
Node has features for files and things that are not permitted in the browser security sandbox.
How long it takes to learn the special Node features depends on how good you are with JS.
Thanks a bunch, I'm so glad I found your channel. In my case, I wanted to create a notification event that should be dispatched on the whole page. I created an empty div for it and dispatched the event on it but this seems wrong. I wonder if there's a way to dispatch in the whole page without having to assign it to a certain element.
Edit: document.dispatchEvent(event) did it
Events can be attached to any object. It doesn't have to be a DOM element. There are event types which are specific to the DOM, like click. These ones tend to be easier to demonstrate.
You can build a plain JS Object and your own invented event and have your JS Object dispatch the event. Your JS Object can listen for the event happening too.
The PubSub design pattern does something like this - ruclips.net/video/aynSM8llOBs/видео.html
It just uses methods like "publish" and "subscribe" instead of dispatchEvent and addEventListener. The concept is the same though.
@@SteveGriffith-Prof3ssorSt3v3 very interesting. Thanks a lot Steve your videos are supplying me with priceless knowledge these days
it's crazy how much more complicated they make this in javascript than C# (where i'm coming from)
Well that's what happens when you get one guy to create a language in a couple weeks and then have several different companies fighting over language features to add or update for 20 years.
Is there a way to dispatch events from an element such that the event can be detected by CHILDREN of the dispatching element?
Events have a target. The event can bubble away from the target up through the Dom to the body and html element.
Or it can move through the elements towards the target down from the html and body. It stops or starts from the target but doesn't go outside that.
If a child element was the target of the event then it would be Ble to listen for it.
Its considered bad practice to add EventListeners to elements in the dom that will be deleted. A better approach it to add the EventListener to the parentNode.
There's nothing wrong with adding the listener to an element that will be deleted. Best practice is to call removeEventListener on the element before deleting it.
Thats the wonderful thing about coding; there are countless approaches that lead to the same results. My approach takes less coding, by letting the event bubble to the parent node. This way there is no need to use the removeEventListener. But to each their own.
Absolutely. I have done that approach before as well. Appreciate the input.
Steve, help me to convert the timestamp to the local time. I tried it with toLocaleString(), but nothing happened jsfiddle.net/xreider/57ockf13/
A timestamp is just a number. It is not a data object. If you want to convert a timestamp into a a Date String then you need to pass that timestamp to the date constructor :
let dt = new Date(myTimeStamp);
Now you will have a date object that includes the toLocaleString method.
@@SteveGriffith-Prof3ssorSt3v3 thanks! it works jsfiddle.net/xreider/zbgp1Lna/1/
How can you target a particular element? e.g. target a child element to listen for an event emitted by its parent.
That's not really how events in the browser work - with an emitter and receiver.
An element can listen for an event of a specific type.
To listen for an event you attach an event listener function to the element by using addEventListener().
We can create an Event object and dispatch it on any element. If that element has an event listener function then that function will be triggered to run.
By default, events bubble up from the element where they were triggered (the event target) up through all parent elements up to the element.
But the listeners can use the capture phase instead of the bubbling phase, which means the event is starting at the html element and go down through the children to reach the target.
You can have a listener on every element in between the target and html and every listener would be triggered by that one event.
I have a whole playlist talking about event handling methods and properties.
@@SteveGriffith-Prof3ssorSt3v3 Interesting so is it impossible to have a parent object emit an event and have all of its children listen for the event?
@Long John if the parent is the target for the event then it only travels between there and the html element.
If the child is the target then every parent ancestor can be aware