limco
limco

Reputation: 1410

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!

Upvotes: 0

Views: 49

Answers (1)

Joshua K
Joshua K

Reputation: 2537

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

Upvotes: 2

Related Questions