Deprecated Event Creation Mechanisms

Alex Reardon
InstructorAlex Reardon

Share this video with your friends

Send Tweet
Published 6 months ago
Updated 5 months ago

There are some deprecated mechanisms for creating events that should be avoided.

Instructor: [0:00] There is a deprecated way to create events, and so if you lean on it, your code may stop working in browsers. We use document.createEvent() and we pass in the event type that we're trying to create. In this case, I'm just creating a standard event, and then we have a separate step to initialize the event.

[0:17] We call the event, which I've called deprecated.initEvent(), and you pass in the event type, and then whether the event will bubble, and then whether the event is cancelable.

[0:28] These two calls here are equivalent to creating an event with the new event constructor, passing in "Hello" as the event type, and then in our EventInit object, we're passing in bubbles: true, cancelable: false.

[0:42] We can use document.createEvent to create events of other types. Here, I'm creating a MouseEvent. The different event types have their own initializer functions. Here, I've got initMouseEvent(), and I'm passing in click.

[0:55] The initMouseEvent function can take up to 15 different arguments to control the properties about a MouseEvent. If I don't provide these properties, then the defaults will be used. We can come in here and say that the default value is being populated.

[1:10] Let's say I wanted to change the button value. What do I have to do? It turns out you have to do something terrible like this. Because initMouseEvent takes an ordered list of arguments rather than an object, you have to provide the values all the way up to the one you want.

[1:26] I'm passing in click because that's what I want and now I'm passing in undefined for all these values that they will default to their default values, going all the way down here. Cool. I can now pass in a different button value. Log that out to the console. I was able to change the button value.

[1:50] We can express the exact same creation of a MouseEvent using the MouseEvent constructor passing in click as the event type and then button 1. This little piece of code here is equivalent to all of this.

[2:03] If I log out my new event, I'll see that I was able to update the button property to 1.