I'm trying to add a confirm dialogue check before the handler executes for a .on("click") event in jquery. This is the original:
$(this.var_mainSelector).on("click",
this.var_acceptOfferSelector,
this.onAcceptOffer
);
I've tried:
$(this.var_mainSelector).on("click", this.var_acceptOfferSelector,
function() {
var test = confirm("are u sure?");
if(test) {
this.onAcceptOffer
}
}
Thanks in advance!
almost ;) the closure itself defines a new "this", so this.onAcceptOffer
isn't defined anymore.
Solutions
1) save this in self
var self = this;
$(this.var_mainSelector).on("click", this.var_acceptOfferSelector, function(evt) {
var test = confirm("are u sure?");
if(test) {
self.onAcceptOffer.call(this, evt);
}
});
2) Don't use function
. Instead use ()=>
$(this.var_mainSelector).on("click", this.var_acceptOfferSelector, (evt)=>{
var test = confirm("are u sure?");
if(test) {
this.onAcceptOffer.call(null, evt); // original "this" (the clicked element) is lost
}
});
arrow functions ("()=>") are not changing the context of the function
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.