• 카테고리

    질문 & 답변
  • 세부 분야

    프로그래밍 언어

  • 해결 여부

    해결됨

선생님께서 ES5 심화과정에서 알려주신 event 처리 방법 나이스입니다!

21.04.26 18:43 작성 조회수 116

1

일전에 ES5 심화과정 에서 event 처리시에 this 를 참조하지 못해서 bind 를 이용해서 해결하신다고 알려주셨는데, 제 나름대로 활용을 해봤습니다.

아직은 많이 미숙하지만 이게 정말 되는게 너무 신기하네요.

덕분에 많이 배우며 성장하고 있습니다. 항상 좋은강의 감사드립니다!

var obj = {
yellowPoint: 100,
redPoint: 200,
bluePoint: 300,
setEvent: function () {
var node = document.querySelector('.sports');
for (let k = 0; k < node.children.length; k++) {
node.children[k].onclick = this.myEvent.bind(obj, k);
}
},

myEvent: function (k, event) {
switch (k) {
case 0:
event.target.style.background = 'yellow';
console.log('k : ', k);
console.log('yellowPoint : ', this.yellowPoint);
break;
case 1:
event.target.style.background = 'red';
console.log('k : ', k);
console.log('redPoint : ', this.redPoint);
break;
case 2:
event.target.style.background = 'blue';
console.log('k : ', k);
console.log('bluePoint : ', this.bluePoint);
break;
}
}
};

obj.setEvent();

답변 1

답변을 작성해보세요.

1

좋습니다.^^ 아래처럼 할 수도 있습니다. ES6 문법 포함

var obj = {
  setEvent() {
    const nodes = document.querySelectorAll('.sports');
    Array.from(nodes, (node, index) => {
      node.onclick = this.myEvent.bind(this, index, node);
    }, obj);
  },
  myEvent: function (index, node, event) {
    console.log(index);
  }
};
obj.setEvent();

twosom님의 프로필

twosom

질문자

2021.04.27

감사합니다! 많은 도움 되었습니다~!

하루빨리 Tensorflow.js 파트까지 마스터하고싶네요! 더욱 열심히 하겠습니다~

응원합니다^^