program story

ES6 화살표 함수와 함께 jQuery $ (this) 사용 (이 바인딩 어휘)

inputbox 2020. 8. 20. 08:17
반응형

ES6 화살표 함수와 함께 jQuery $ (this) 사용 (이 바인딩 어휘)


어휘 this바인딩 과 함께 ES6 화살표 기능을 사용하는 것이 좋습니다.

그러나 잠시 전에 일반적인 jQuery 클릭 바인딩과 함께 사용하여 문제가 발생했습니다.

class Game {
  foo() {
    self = this;
    this._pads.on('click', function() {
      if (self.go) { $(this).addClass('active'); }
    });
  }
}

대신 화살표 기능 사용 :

class Game {
  foo() {
    this._pads.on('click', () => {
      if (this.go) { $(this).addClass('active'); }
    });
  }
}

그런 다음 $(this)ES5 (self = this) 유형 클로저로 변환됩니다.

Traceur가 어휘 바인딩에 대해 "$ (this)"를 무시하도록하는 방법이 있습니까?


이것은 Traceur와 관련이 없으며 무언가를 끄는 것과 관련이 없습니다. 이것은 단순히 ES6가 작동하는 방식입니다. =>대신을 사용하여 요구하는 특정 기능 입니다 function () { }.

ES6를 작성하려면 항상 ES6를 작성해야하며 특정 코드 줄에서 전환 할 수 없으며 =>작동 방식을 억제하거나 변경할 수 없습니다 . 당신이 할 수 있다고하더라도, 당신은 단지 당신 만이 이해하고 사용자 정의 된 Traceur 외부에서는 제대로 작동하지 않는 기괴한 버전의 JavaScript를 보게 될 것입니다. 이것은 확실히 Traceur의 요점이 아닙니다.

이 특정 문제를 해결하는 방법 this은 클릭 한 요소에 대한 액세스 권한을 얻는 데 사용 하는 것이 아니라 다음을 사용하는 것입니다 event.currentTarget.

Class Game {
  foo(){
    this._pads.on('click', (event) => {
      if(this.go) {
        $(event.currentTarget).addClass('active');
      }
    });
  }
}

jQuery는 event.currentTarget특히 ES6 이전에도 jQuery가 this콜백 함수 를 부과하는 것이 항상 가능하지는 않기 때문에 제공 합니다 (즉, bind.


이벤트 바인딩

$button.on('click', (e) => {
    var $this = $(e.currentTarget);
    // ... deal with $this
});

고리

Array.prototype.forEach.call($items, (el, index, obj) => {
    var $this = $(el);
    // ... deal with $this
});

또 다른 경우

The top answer is correct and I've up-voted it.

However, there is another case:

$('jquery-selector').each(() => {
    $(this).click();
})

Could be fixed as:

$('jquery-selector').each((index, element) => {
    $(element).click();
})

(This is an answer I wrote for another version of this question, before learning it was a duplicate of this question. I think the answer pulls together the information fairly clearly so I decided to add it as a community wiki, although it's largely just different phrasing of the other answers.)

You can't. That's half the point of arrow functions, they close over this instead of having their own that's set by how they're called. For the use case in the question, if you want this set by jQuery when calling the handler, the handler would need to be a function function.

But if you have a reason for using an arrow (perhaps you want to use this for what it means outside the arrow), you can use e.currentTarget instead of this if you like:

class Game {
  foo(){
    this._pads.on('click', e => {                   // Note the `e` argument
      if(this.go) {
        $(e.currentTarget).addClass('active');      // Using it
      }
    });
  }
}

The currentTarget on the event object is the same as what jQuery sets this to when calling your handler.


As Meager said in his answer on this same question If you want to write ES6, you need to write ES6 all the time,

so if you are using arrow function of ES6: (event)=>{}, then you have to use $(event.currentTarget) instead of $(this).

you can also use more nicer and cleaner way of using currentTarget as ({currentTarget})=>{},

Class Game {
  foo(){
    this._pads.on('click', ({currentTarget}) => {
      if(this.go) {
        $(currentTarget).addClass('active');
      }
    });
  }
}

originally this idea was commented by rizzi frank in @Meager's answer, and i felt it useful and i think that not all people will read that comment so i have written it as this another answer.

참고URL : https://stackoverflow.com/questions/27670401/using-jquery-this-with-es6-arrow-functions-lexical-this-binding

반응형