Using HTML attributes event handlers and object property event handlers are related ways of expressing a single event listener binding to an element. This lesson explores the dynamics and often strangeness of that relationship.
Instructor: [0:00] HTML attribute event handlers and object property event handlers are linked ways of expressing an event handler binding. On close inspection, there are some interesting characteristics to their relationship.
[0:14] First up, you can only use one binding mechanism or the other. You cannot have both. Setting one will override the other. Here, I am rendering my HTML with an onclick attribute on my button element.
[1:28] If I have a HTML attribute event handler, I can clear that event handler in two different ways. Firstly, I can remove the HTML attribute completely to unbind the event handler. I can also clear the event handler by setting the onclick property on my button element to null.
[1:52] If we take a look at our HTML, we'll see that our onclick HTML attribute is sitting there happily unmodified, even though the event handler has been unbound. This behavior is different to other element properties, such as ID. Here, my button has an ID of original ID. We can see it over here in the element panel as well.
[2:53] The utility of this behavior is super limited, as you're not actually creating or dispatching an event, you're just executing the onclick function. I'm going to change this onclick function to logout the this runtime context and the event.
[3:09] If we look over at the event panel, we can see that that this runtime context was set correctly to be the button, which is the element that the event handler is bound to. Our event object is undefined, which makes sense because we're not creating any events or parsing any events into this function.
[3:27] Technically, you can parse in an event to an onclick function to populate the event. However, the ability to execute event handlers directly has extremely limited utility. I personally have never written code like this. I will cover how you can create and dispatch your own events in my synthetic events lesson.