javascript - Scope of this in click handler ECMA script 6 -


as scope of this becomes available in es6 arrow functions.

but here case in unable access this in arrow function while working normal anonymous function

example

sample 1

$(document).ready(function() {     $('.principal').click(() => {         alert($(this).parent().html()); // 'this' undefined here     }); }) 

sample 2

$(document).ready(function() {     $('.principal').click(function() {         alert($(this).parent().html()); // 'this' available here     }); }) 

the reason jquery explicitly binds this object in click handler element on event captured. way context using standard function, since indeed arrow function ignores binding.

so need either:

  • stick standard function callback, or
  • use currenttarget property of event object argument jquery passes callback

the latter so:

$(document).ready(function() {      $('.principal').click((e) => {          console.log($(e.currenttarget).parent().html());      });  })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>  <div><button class="principal">click me</button></div>

outputs:

<button class="principal">click me</button> 

Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

ios - Change Storyboard View using Seague -