<HTML>
<body>
<div id="menu>
<button data-action="save">Save</button>
<button data-action="load">Load</button>
<button data-action="search">Search</button>
</div>
<script>
class Menu {
constructor(elem) {
this._elem = elem;
elem.onclick = this.onClick.bind(this); //-
//without the binding in here,
//it would reference the DOM element 'elem'
//not the menu object
}
save() {
alert('saving');
}
load(){
alert('load');
}
search(){
alert('search');
}
onClick(event) {
let action = event.target.dataset.action;
//event.target = button
//event.target.dataset.action = button data-action="save"
//means the DATA-ACTION ATTRIBUTE VALUE. the word
if(action) {
this[action]();
//run the function
//without binding it would not work as we menat
}
};
}
new Menu(menu);
</script>
</body>
</HTML>
<body>
<div id="menu>
<button data-action="save">Save</button>
<button data-action="load">Load</button>
<button data-action="search">Search</button>
</div>
<script>
class Menu {
constructor(elem) {
this._elem = elem;
elem.onclick = this.onClick.bind(this); //-
//without the binding in here,
//it would reference the DOM element 'elem'
//not the menu object
}
save() {
alert('saving');
}
load(){
alert('load');
}
search(){
alert('search');
}
onClick(event) {
let action = event.target.dataset.action;
//event.target = button
//event.target.dataset.action = button data-action="save"
//means the DATA-ACTION ATTRIBUTE VALUE. the word
if(action) {
this[action]();
//run the function
//without binding it would not work as we menat
}
};
}
new Menu(menu);
</script>
</body>
</HTML>
댓글
댓글 쓰기