# object handler

[JS](https://lochiwei.gitbook.io/web/js) ⟩ [browser](https://lochiwei.gitbook.io/web/browser) ⟩ [event](https://lochiwei.gitbook.io/web/browser/event) ⟩ [handler](https://lochiwei.gitbook.io/web/browser/event/handler) ⟩ [register](https://lochiwei.gitbook.io/web/browser/event/handler/register) ⟩ object handler

{% hint style="success" %}
delegate event handling to an <mark style="color:yellow;">**object**</mark>：

```javascript
elem.addEventListener('click', {
    // calls handleEvent(event) in case of an event.
    handleEvent(event) { ... }    // ⭐️ required method
});
```

{% endhint %}

{% tabs %}
{% tab title="⭐️ 重點" %}
{% hint style="info" %}
could also use a [class](https://lochiwei.gitbook.io/web/js/val/class "mention") instance for that:
{% endhint %}

```javascript
class Menu {
    // ⭐️ required method
    handleEvent(event) {
      switch(event.type) {
        case 'mousedown': ...; break;
        case 'mouseup'  : ...; break;
      }
    }
    // other methods/properties ...
}

// Menu can also be written like this:
class Menu {

    // ⭐️ required method
    handleEvent(event) {
      const methodName = "on" + event.type;  // onmousedown, onmouseup ...
      this[methodName] ?. (event);           // optional invocation
    }
    
    // methods for individual event
    onmousedown(event){ ... }
    onmouseup  (event){ ... }
}

let menu = new Menu();    // object handler

elem.addEventListener('mousedown', menu);
elem.addEventListener('mouseup'  , menu);
```

{% endtab %}

{% tab title="👥 相關" %}

* [optional-invocation-.](https://lochiwei.gitbook.io/web/js/val/obj/prop/access/optional-invocation-. "mention")
  {% endtab %}

{% tab title="📗 參考" %}

* [ ] JS.info ⟩ [object handlers](https://javascript.info/introduction-browser-events#object-handlers-handleevent)
  {% endtab %}
  {% endtabs %}
