Reputation: 9702
Im new to jquery..I have written a jquery function to process some form inputs. I see an strange issue that my $(document).ready(function(){}
is getting called twice.
My form is;
<form>
...........
<div class="form-actions" id="saveButtons">
<button class="btn btn-primary" /><%=i18n.localize("save")%></button>
<%if(outputs.isPermitted){%><script> </script><a class="btn btn-info" id="publish_api" >Save & Publish</a> <%}%>
<input type="reset" class="btn" value="<%=i18n.localize("cancel")%>" onclick="javascript:window.location.href='./'" />
</div>
</form>
And the jquery is;
<script>
$(document).ready(function(){
$('#publish_api').click(function(e){
$("body").on("api_saved", function(e){
$.ajax({
........
});
$("#manage_form").submit();
});
</script>
I see above alert twice when i click save and publish
button. This issue occurs if there any user error in filling the form. (That is, if user does not fill a MUST field and agin if he filled that entry and try to click the button) What would be the cause?
Edit; The "api-saved" event handler is called from a javascript like; (to validate all params in that form)
var v = $("#manage_form").validate({
submitHandler: function(form) {
if(!validate_tiers()){
return false;
}
$('#saveMessage').show();
$('#saveButtons').hide();
$(form).ajaxSubmit({
success:function(responseText, statusText, xhr, $form) {
$('#saveMessage').hide();
$('#saveButtons').show();
if (!responseText.error) {
$( "body" ).trigger( "api_saved" );
} else {
.........
}
Upvotes: 0
Views: 348
Reputation: 413916
You're nesting event handler assignment, which is usually a bug. You've got:
$('#publish_api').click(function(e){
which establishes a handler for the "click" event from an element. Inside that event handler is code that sets up another event handler:
$("body").on("api_saved", function(e){
alert("calling lifecycle jag");
// ...
The reason that's likely to be a bug is that every call to .on()
inside the "click" handler will attach a separate copy of that event handler. After clicking twice, there will be two identical handlers for the "api_saved" event. After clicking 5 times, there'll be 5 handlers, and so on. That happens because a call to .on()
does not remove event handlers that are already registered.
Probably the right thing to do is move that event handler assignment (the one for "api_saved") out of the "click" handler.
Upvotes: 2