javascript - How to prevent overwriting context this in ES6 -


this question has answer here:

very similar how prevent jquery override "this" in es6.

this class:

class feedbackform {   constructor(formel) {     this.$form = $(formel)     this.$form.submit(this.sendstuff)      this.alerts = $('#something');   }    /**    * sends feedback    * @param {event} e    */   sendstuff(e) {     e.preventdefault()      if (this.alerts.length) {       window.alert('notice... stuff')     }      $.ajax({       type: this.$form.prop('method'),       url: this.$form.prop('action'),       data: this.$form.serialize()     }).done(() => window.location.reload(true))   } } 

the sendstuff method event handler of form, , jquery calls using function.prototype.apply believe. therefore, this inside sendstuff overwritten event target jquery applies , can't access this.alerts or other property methods.

i'm not sure if can apply var = this trick here or how work around issue?

you can use arrow function:

an arrow function expression (also known fat arrow function) has shorter syntax compared function expressions and lexically binds value

this should it:

this.$form.submit(e => this.sendstuff(e)); 

Comments

Popular posts from this blog

how to insert data php javascript mysql with multiple array session 2 -

multithreading - Exception in Application constructor -

windows - CertCreateCertificateContext returns CRYPT_E_ASN1_BADTAG / 8009310b -