본문 바로가기

Study/Web

[js] 클래스 안 EvnetListener에서 클래스에 있는 메소드 이용하기

개요


html이 아래처럼 구성되어있다고 하자.

<h1 id = "title"> TODO List </h1>

 

TODO List라는 h1타이틀에 이벤트 리스너를 붙여보자. 클릭하면 알람이 나오도록.

 

보통 이벤트 리스너를 붙이는 방법은 세 가지다.

 

1. 익명함수 이용하기

$title = document.querySelector("#title");
this.$title.addEventListener("click", function(){
    alert(this.innerText);  //TODO List
});

 

2. 이벤트용 함수 이용하기

$title.addEventListener("click", alertValue);
function alertValue(){
   alert("title clicked");
}

 

3. 매개변수가 필요할땐 익명함수 안에 이벤트함수를 넣기

$title.addEventListener("click", function(){
    alertValue("hello");
});
function alertValue(str){
    alert(str);
}

 

 

 

문제


그런데 클래스 안에서 이용한다면? 이벤트 리스너 콜백에 들어가는 this는 이벤트 객체 자체를 가리키게 된다.

그래서 클래스의 메소드를 사용할수가 없다. (클래스의 메소드를 쓸때는 this.메소드이름()으로 쓰는데 못 한다.)  ㅠㅠ

클래스의 alertValue를 쓰려면 어떻게 해야할까?

 

export default class Todo {

    $title = document.querySelector("#title");

	constructor($target) {
        this.$title.addEventListener("click", function(){
            // this.alertValue("hello");   //this는 이벤트가 일어난 객체를 의미한다
            alert(this.innerText);         //"TODO List"
        });
    }

    alertValue(str){
        alert(str);
    }
}

 

 

 

해결


화살표함수를 이용한다. 화살표함수 내부의 this는 항상 상위 스코프의 this를 가리킨다.

따라서, 메소드 내부라면 이때 this는 클래스를 가리킨다.

 

export default class Todo {
    $title = document.querySelector("#title");
  
    constructor() {
    	//"TODO List" 출력
        this.$title.addEventListener("click", (e)=>{this.alertValue(e.target);});	
    }

    alertValue(elem){
        alert(elem.innerText);
    }
}