---
# System prepended metadata

title: 'JS: handleEvent'
tags: [js]

---

# JS: handleEvent

HTML:
```htmlmixed=
<input id="msg" type="text" value="msg123456">

<div id="output"></div>
```

JS:
```javascript=
let msg;
let output;

let main = {
    init: function(){
        msg = document.getElementById('msg');
        output = document.getElementById('output');
        
        msg.addEventListener('input', this, false);
        // 這邊的 this == main, 且為 object
        // event發生時會觸發 main.handleEvent(e)
    },
    handleEvent: function(e){
        // 這邊寫if是為了保留將來可以增加其他event或其他指定元素的空間
        if(e.type == 'input'){
            if(e.target.id == 'msg'){
                this.msgOnChange(e.target.value);
            }
        }
    },
    msgOnChange: function(v){
        output.innerText(v);
    }
};

(function(){
    main.init();
})();
```

## 參考資料

* [handleEvent與addEventListener](http://www.ayqy.net/blog/handleevent%E4%B8%8Eaddeventlistener/)
* [addEventListener之handleEvent](https://www.jianshu.com/p/13a0e7f4c335)


###### tags: `js`