limco limco - 1 month ago 12
jQuery Question

Add confirm dialogue check before .on() event handler

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!

Answer Source

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