I am setting the submit function on a form with jQuery then later in the process I reset the function to something else. What happens is the original function gets called again then the new function when only the new function should have been called.
I am sending the requests with AJAX. The first one validated the values on the server then asks if you want to continue. Clicking the submit again should only call the changed function but for some reason both get called simultaneously with a single click.
What is happening here? Could jQuery be delaying the the setting of the 2nd function on the form submit?
Edit: These are the methods that change the handler.
_confirmationCB: function(json, status) {
this._setMessage(json['message']);
if(json['valid']) {
$('form#form').unbind('submit', this._confirmationRequest);
$('form#form').submit(this._deleteRequest.bindObject(this));
}
},
_deleteCB: function(json, status) {
this._setMessage(json["message"]);
if(json['valid']) {
this._setMessage(json["message"]);
$('td input[type=checkbox]').each(function() {
if(this.checked) {
$(this).parent().parent().remove();
}
});
}
$('form#form').unbind('submit', this._deleteRequest);
$('form#form').submit(this._confirmationRequest.bindObject(this));
this._setMessage(true);
},
I am not showing all the code here as the class is somewhat long.
Edit: I just tried unbinding the handler, but it had no effect on the issue I am having.
This is the bindObject function:
Function.prototype.bindObject = function(object) {
var method = this;
return function () {
method.apply(object, arguments);
};
}
This is not really relevant to the issue I’m having, but somebody asked for it. It is used to bind the class ‘this’ object to methods when called by jQuery $.ajax.
Have you unbound the previous handler before binding the new one? Can you share some code?
Edit: Actually your bindObject function has a lot to do with this. The bindObject function returns an anonymous function handler but what you are unbinding is a concrete handler viz. a function name like _deleteRequest etc. This won’t work. Binding and unbinding only work if the same handler is being bounded and removed. So you should probably save the return from bindObject in some var & then use that var to call bind & unbind.