This commit is contained in:
Ilya Kantor 2019-08-01 18:39:59 +03:00
parent e6e562040d
commit b6b06f6b35

View file

@ -162,15 +162,15 @@ button.onclick = sayThanks();
If we add parentheses, `sayThanks()` -- is a function call. So the last line actually takes the *result* of the function execution, that is `undefined` (as the function returns nothing), and assigns it to `onclick`. That doesn't work. If we add parentheses, `sayThanks()` -- is a function call. So the last line actually takes the *result* of the function execution, that is `undefined` (as the function returns nothing), and assigns it to `onclick`. That doesn't work.
...But in the markup we do need the parentheses: ...On the other hand, in the markup we do need the parentheses:
```html ```html
<input type="button" id="button" onclick="sayThanks()"> <input type="button" id="button" onclick="sayThanks()">
``` ```
The difference is easy to explain. When the browser reads the attribute, it creates a handler function with the body from its content. The difference is easy to explain. When the browser reads the attribute, it creates a handler function with *body from its content*: `sayThanks()`.
So the last example is the same as: So the markup generates this property:
```js ```js
button.onclick = function() { button.onclick = function() {
*!* *!*
@ -351,7 +351,7 @@ Some properties of `event` object:
: Event type, here it's `"click"`. : Event type, here it's `"click"`.
`event.currentTarget` `event.currentTarget`
: Element that handled the event. That's exactly the same as `this`, unless the handler is an arrow function, or its `this` is bound to something else, then `event.currentTarget` becomes useful. : Element that handled the event. That's exactly the same as `this`, unless the handler is an arrow function, or its `this` is bound to something else, then we can get the element from `event.currentTarget`.
`event.clientX / event.clientY` `event.clientX / event.clientY`
: Window-relative coordinates of the cursor, for mouse events. : Window-relative coordinates of the cursor, for mouse events.
@ -371,7 +371,7 @@ That's possible because when the browser reads the attribute, it creates a handl
## Object handlers: handleEvent ## Object handlers: handleEvent
We can assign an object as an event handler using `addEventListener`. When an event occurs, its `handleEvent` method is called with it. We can assign not just a function, but an object as an event handler using `addEventListener`. When an event occurs, its `handleEvent` method is called.
For instance: For instance:
@ -388,7 +388,7 @@ For instance:
</script> </script>
``` ```
In other words, when `addEventListener` receives an object as the handler, it calls `object.handleEvent(event)` in case of an event. As we can see, when `addEventListener` receives an object as the handler, it calls `object.handleEvent(event)` in case of an event.
We could also use a class for that: We could also use a class for that: