Javascript - arrow在事件处理程序中执行这个操作? [英] Javascript - arrow functions this in event handler?

查看:90
本文介绍了Javascript - arrow在事件处理程序中执行这个操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



$(this)返回未定义点击?

  dom.videoLinks.click((e)=> {
e.preventDefault();
console.log($(this));
var self = $(this),
url = self.attr(configuration.attribute);

eventHandlers.showVideo url);

//停用任何活动的视频缩略图
dom.videoLinks.filter('。video-selected')。removeClass('video-selected');

//激活所选的视频缩略图
self.addClass('video-selected');
});

但是,如果我更改它不是一个箭头函数它按预期工作?:

  dom.videoLinks.click(function(e){
e.preventDefault() ;
console.log(this);
console.log($(this));
var self = e.this,
url = self.attr(configuration.attribute );

eventHandlers.showVideo(url);

//停用任何活动的视频缩略图
dom.videoLinks.filter('。video-selected')。 removeClass('video-selected');

//激活所选的视频缩略图
self.addClass('video-selected');
});

所以如果我使用箭头函数,我该怎么办回调?

解决方案

使用 arrow function 作为回调,而不是使用 / code>获取处理程序所绑定的元素,您应该使用 event.currentTarget

这个在箭头函数内部由箭头函数定义的位置确定,而不是使用
所以从现在开始请注意,
event.currentTarget 始终指向 DOM 元素,其EventListeners正在处理。






.currentTarget vs .target



使用 event.currentTarget 而不是 event.target 因为事件冒泡/捕获




  • event.currentTarget - 是附加了事件侦听器的元素。

  • event.target - 是触发事件的元素。



从文档:


currentTarget 类型为 EventTarget ,readonly用于指示
EventTarget EventListeners 正在处理中。这个
在捕获和冒泡期间特别有用。


检查

data-hide =true>

  = document.getElementById('parent'); parent.addEventListener('click',function(e){document.getElementById('msg')。innerHTML =this:+ this.id +< br> currentTarget: + e.currentTarget.id +< br> target:+ e.target.id;}); $('#parent')。on('click',function(e){$('#jQmsg ').html(* jQuery< br> this:+ $(this).prop('id')+< br> currenTarget:+ $(e.currentTarget).prop('id' < br> target:+ $(e.target).prop('id'));}); $('#parent')on('click',e => $('#arrmsg ')的.html(' *箭头函数< br> currentTarget:'+ e.currentTarget.id));  

  #parent {background-color:red;宽度:250像素; height:220px;}#child {background-color:yellow; height:120px; width:120px; margin:0 auto;}#grand-child {background-color:blue; height:50px; width:50px; margin:0 auto;}#msg,#jQmsg,#arrmsg {font-size:16px; font-weight:600; background-color:#eee; font-family:sans-serif; color:navy;}  

 < script src =https://ajax.googleapis.com/ajax/库/ jquery的/ 2.1.1 / jquery.min.js>< /脚本> < div id =parent> Parent-(附加的事件处理程序)< br>< br> < div id =child>子< BR><峰; br> < p id =grand-child> Grand Child< / p> < / DIV> < / DIV> < div id =msg>< / div>< br> < div id =jQmsg>< / div>< br> < div id =arrmsg>< / div>  


I'm new to ES6, and can't quite get this to work:

$(this) returns undefined on click?

dom.videoLinks.click((e) => {
            e.preventDefault();
            console.log($(this));
            var self = $(this),
                url = self.attr(configuration.attribute);

            eventHandlers.showVideo(url);

            // Deactivate any active video thumbs
            dom.videoLinks.filter('.video-selected').removeClass('video-selected');

            // Activate selected video thumb
            self.addClass('video-selected');
        });

However if I change it so not be an arrow function like so, it works as expected?:

dom.videoLinks.click(function(e) {
            e.preventDefault();
            console.log(this);
            console.log($(this));
            var self = e.this,
                url = self.attr(configuration.attribute);

            eventHandlers.showVideo(url);

            // Deactivate any active video thumbs
            dom.videoLinks.filter('.video-selected').removeClass('video-selected');

            // Activate selected video thumb
            self.addClass('video-selected');
        });

So how would I go about it if I use an arrow function in the callback?

解决方案

With arrow function as a callback, instead of using this to get the element to which the handler is bound, you should use event.currentTarget.
Value of this inside an arrow function is determined by where the arrow function is defined, not where it is used.
So from now on, keep in mind that event.currentTarget always refers to the DOM element whose EventListeners are currently being processed.


.currentTarget vs .target

Use event.currentTarget instead of event.target because of event bubbling/capturing:

  • event.currentTarget- is the element that has the event listener attached to.
  • event.target- is the element that triggered the event.

From the documentation:

currentTarget of type EventTarget, readonly Used to indicate the EventTarget whose EventListeners are currently being processed. This is particularly useful during capturing and bubbling.

Check the basic example in the below snippet

var parent = document.getElementById('parent');
parent.addEventListener('click', function(e) {
  
  document.getElementById('msg').innerHTML = "this: " + this.id +
    "<br> currentTarget: " + e.currentTarget.id +
    "<br>target: " + e.target.id;
});

$('#parent').on('click', function(e) {

  $('#jQmsg').html("*jQuery<br>this: " + $(this).prop('id')
                   + "<br>currenTarget: " + $(e.currentTarget).prop('id') 
                   + "<br>target: " + $(e.target).prop('id'));
});

$('#parent').on('click', e => $('#arrmsg').html('*Arrow function <br> currentTarget: ' + e.currentTarget.id));

#parent {background-color:red; width:250px; height:220px;}
#child {background-color:yellow;height:120px;width:120px;margin:0 auto;}
#grand-child {background-color:blue;height:50px;width:50px;margin:0 auto;}
#msg, #jQmsg, #arrmsg {font-size:16px;font-weight:600;background-color:#eee;font-family:sans-serif;color:navy;}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

  <div id="parent">Parent-(attached event handler)<br><br>
    <div id="child"> Child<br><br>
      <p id="grand-child">Grand Child</p>
    </div>
  </div>
 
  <div id="msg"></div><br>
  <div id="jQmsg"></div><br>
  <div id="arrmsg"></div>

这篇关于Javascript - arrow在事件处理程序中执行这个操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆