I am trying to follow the modular js design pattern (revealing) and I have a question. When I bind event listeners like so:
$addClient.submit(ajaxCall);
The event ajaxCall
does not run on load. However, when I add parenthesis, like so:
$addClient.submit(ajaxCall());
...it runs on load and does not bind to the event. What gives? I want to add an argument to the ajaxCall()
function, but I cannot seem to get it working correctly. Just so you have context, here is the whole code:
var Ajax = (function(){
var $addClient = $('#add_client');
$addClient.submit(ajaxCall);
function ajaxCall(clearFields) {
console.log('function called');
var data = $(this).serialize();
var url = this.action;
$.ajax({
type: 'POST',
url: url,
dataType: 'json',
data: data,
success: function(data) {
if(data.st === 0) {
$messageContainer.html('<p class="alert alert-danger">' + data.msg + '</p>');
setTimeout(function(){
$messageContainer.html('');
}, 7000);
} else {
$messageContainer.html('<p class="alert alert-success">' + data.msg + '</p>');
if(clearFields === true) {
$('input[type="text"]').val('');
$('input[type="email"]').val('');
$('textarea').val('');
}
setTimeout(function(){
$messageContainer.html('');
}, 7000);
}
}
});
return false;
}
})();