Resolved
Written on
·
195
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();
Answer 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();
감사합니다! 많은 도움 되었습니다~!
하루빨리 Tensorflow.js 파트까지 마스터하고싶네요! 더욱 열심히 하겠습니다~