Это видео недоступно.
Сожалеем об этом.

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...

Комментарии • 59

  • @maxkehayov
    @maxkehayov 6 лет назад +9

    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!

  • @NeilTruick
    @NeilTruick 5 лет назад +2

    Yes, yes, YES! "Crystal clear" is an understatement regarding the explanation and the presentation...
    Great tutorial, Steve...thank you!

  • @RedEyedJedi
    @RedEyedJedi 4 года назад

    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.

  • @Snoo29293
    @Snoo29293 3 года назад

    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.

  • @expukpuk
    @expukpuk 6 лет назад +1

    Perfect clarity! Thanks Mate.

  • @ibknl1986
    @ibknl1986 3 года назад

    Perfect explanation. Thank you for the video.

  • @GPTalksZone
    @GPTalksZone 2 года назад

    Good explanation 👍👍👍

  • @ankitrajput85
    @ankitrajput85 6 лет назад

    Thanks, Steve! This is what I was looking for. Perfect!

  • @friendmusic7141
    @friendmusic7141 6 лет назад +2

    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.

    • @SteveGriffith-Prof3ssorSt3v3
      @SteveGriffith-Prof3ssorSt3v3  6 лет назад +1

      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.

    • @friendmusic7141
      @friendmusic7141 6 лет назад

      That's a great example. Thank you!

    • @pyrofred11691
      @pyrofred11691 4 года назад

      What do you mean by "the code inside the event"?

  • @nasaruddin36
    @nasaruddin36 5 лет назад +1

    Perfect tutorial on custom event...

  • @pumbo_nv
    @pumbo_nv 2 года назад

    I believe modern browsers will automatically GC event listeners on a removed element as long as it's not referenced anywhere.

    • @SteveGriffith-Prof3ssorSt3v3
      @SteveGriffith-Prof3ssorSt3v3  2 года назад

      GC has improved over the years but it is the not referenced part that is most challenging for junior developers.

  • @henrywang2106
    @henrywang2106 6 лет назад

    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!

    • @SteveGriffith-Prof3ssorSt3v3
      @SteveGriffith-Prof3ssorSt3v3  6 лет назад

      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.

    • @henrywang2106
      @henrywang2106 6 лет назад

      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?

    • @SteveGriffith-Prof3ssorSt3v3
      @SteveGriffith-Prof3ssorSt3v3  6 лет назад

      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.

    • @henrywang2106
      @henrywang2106 6 лет назад +1

      Thanks a lot Steve! Got it working!

  • @Azertuiopnbvcxwmlkjh
    @Azertuiopnbvcxwmlkjh 3 года назад

    Great, very clear 👌

  • @mamoudgad4210
    @mamoudgad4210 15 дней назад

    awesome thanks

  • @sabarishchandramouli6418
    @sabarishchandramouli6418 5 лет назад

    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

    • @SteveGriffith-Prof3ssorSt3v3
      @SteveGriffith-Prof3ssorSt3v3  5 лет назад

      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.

    • @sabarishchandramouli6418
      @sabarishchandramouli6418 5 лет назад +1

      @@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!

  • @mohammadaliafrasiaby2347
    @mohammadaliafrasiaby2347 2 года назад

    What is the difference between appendChild, insertAdjacentHTML
    i dont no
    but
    i think insertAdjacentHTML is cleaner
    is it?

    • @SteveGriffith-Prof3ssorSt3v3
      @SteveGriffith-Prof3ssorSt3v3  2 года назад +1

      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( ).

    • @mohammadaliafrasiaby2347
      @mohammadaliafrasiaby2347 2 года назад

      @@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.

    • @SteveGriffith-Prof3ssorSt3v3
      @SteveGriffith-Prof3ssorSt3v3  2 года назад +1

      @@mohammadaliafrasiaby2347 es6 is vanilla js. Practice is the only thing you can do.

  • @classzaban
    @classzaban 3 года назад

    Awesome

  • @VeaceslavBARBARII
    @VeaceslavBARBARII 3 года назад

    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!

  • @VassiliySmith
    @VassiliySmith Год назад

    Why not use {once:true} option to remove listener automatically

  • @jehontanda7190
    @jehontanda7190 2 года назад

    @steve Griffith, can i also ask something ?

  • @sergiomallmachavez5534
    @sergiomallmachavez5534 4 года назад

    I tried to do a dispatchEvent on a button with disabled state in ie11 but it won't fire it. Help me please :(

    • @SteveGriffith-Prof3ssorSt3v3
      @SteveGriffith-Prof3ssorSt3v3  4 года назад +1

      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.

  • @mohammadaliafrasiaby2347
    @mohammadaliafrasiaby2347 2 года назад

    good job
    after js
    how long does it take to learn node .js???

    • @SteveGriffith-Prof3ssorSt3v3
      @SteveGriffith-Prof3ssorSt3v3  2 года назад +1

      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.

  • @neatpolygons8500
    @neatpolygons8500 3 года назад

    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

    • @SteveGriffith-Prof3ssorSt3v3
      @SteveGriffith-Prof3ssorSt3v3  3 года назад +1

      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.

    • @neatpolygons8500
      @neatpolygons8500 3 года назад +1

      @@SteveGriffith-Prof3ssorSt3v3 very interesting. Thanks a lot Steve your videos are supplying me with priceless knowledge these days

  • @sloppyy
    @sloppyy 4 года назад

    it's crazy how much more complicated they make this in javascript than C# (where i'm coming from)

    • @SteveGriffith-Prof3ssorSt3v3
      @SteveGriffith-Prof3ssorSt3v3  4 года назад +1

      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.

  • @longjohnny
    @longjohnny Год назад

    Is there a way to dispatch events from an element such that the event can be detected by CHILDREN of the dispatching element?

    • @SteveGriffith-Prof3ssorSt3v3
      @SteveGriffith-Prof3ssorSt3v3  Год назад

      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.

  • @suppaduppa
    @suppaduppa 6 лет назад

    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.

    • @SteveGriffith-Prof3ssorSt3v3
      @SteveGriffith-Prof3ssorSt3v3  6 лет назад +2

      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.

    • @suppaduppa
      @suppaduppa 6 лет назад

      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.

    • @SteveGriffith-Prof3ssorSt3v3
      @SteveGriffith-Prof3ssorSt3v3  6 лет назад +2

      Absolutely. I have done that approach before as well. Appreciate the input.

  • @indigosay
    @indigosay 4 года назад

    Steve, help me to convert the timestamp to the local time. I tried it with toLocaleString(), but nothing happened jsfiddle.net/xreider/57ockf13/

    • @SteveGriffith-Prof3ssorSt3v3
      @SteveGriffith-Prof3ssorSt3v3  4 года назад

      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.

    • @indigosay
      @indigosay 4 года назад

      @@SteveGriffith-Prof3ssorSt3v3 thanks! it works jsfiddle.net/xreider/zbgp1Lna/1/

  • @longjohnny
    @longjohnny Год назад

    How can you target a particular element? e.g. target a child element to listen for an event emitted by its parent.

    • @SteveGriffith-Prof3ssorSt3v3
      @SteveGriffith-Prof3ssorSt3v3  Год назад

      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.

    • @longjohnny
      @longjohnny Год назад

      @@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?

    • @SteveGriffith-Prof3ssorSt3v3
      @SteveGriffith-Prof3ssorSt3v3  Год назад

      @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