JavaScript Pattern: Using Custom Events
HTML-код
- Опубликовано: 26 мар 2019
- In JavaScript you can create a custom event and respond to that event using a listener. In this tutorial we will show you how to create a custom event, emit that event, and respond to it with an event listener.
Would you like to help keep this channel going?
/ allthingsjavascript
For more resources on JavaScript:
www.allthingsjavascript.com
Access to EVERY course (get 2 months free): www.skillshare.com/r/profile/...
Courses offered on Udemy at a discount:
Getting Started: www.udemy.com/learn-modern-ja...
Advanced Topics: www.udemy.com/learn-modern-ja...
Mastering Regular Expressions in JavaScript:
www.udemy.com/mastering-regul...
Functional Programming in JavaScript: www.udemy.com/functional-prog...
NEW Mastering JavaScript Arrays: www.udemy.com/course/masterin...
Tutorials referred to in this video:
Understanding Asynchronous JavaScript: • Understanding Asynchro...
Event Bubbling: • JavaScript Questions: ...
#javascript #AllThingsJavaScriptLLC
Thank you, please keep the videos coming!! So good!
Simply awesome short video. It completely made sense to me throughout. I'm gonna implement this for all my projects moving forward.
Thanks for your efforts ❤️
Just found the video, awesome job!! Works great
This is so gold, thanks a lot :)
Wow thanks a lot. very helpful
Thank u for this awesome video
Great!
thx for nice explanation
Glad it helped
how about you talk about Shadow DOM
And using event bubbling to communicate between webcomponents
Why is it I cannot have a custom event created, subscribed to and listened to in the same js file, it only seems to work if I have 2 seperate script files being loaded in? I didnt see your html setup in the video.
You should be able to do it in the same file. Are you getting an error?
Make sure you have your addEventListener code come before your dispatchEvent code.
@@TheCodeCreative Thanks.
Hi, your code doesn't work in 1 single file... absolutely nothing happens... why? thanks for some clues
The eventListener handler needs to be added/registered before you dispatch the event. e.g.
const loginEvent = new CustomEvent('login', {
detail: {
firstTime: true
}
})
// listener added to document first
document.addEventListener('login', (event) => {
console.dir(event)
})
// can now dispatch the event and it will be caught
document.dispatchEvent(loginEvent)
@@Russ_Paul thanks Paul)
@@user-ty5pd4xw2y You're welcome.
Can you supply the code you used?
Is there ANY way to have a parent element emit/ dispatch an event which can be 'heard' by its child elements?
I believe you can do this with some JavaScript libraries, but this is not something I have tried.