Reputation: 135
I have generic function i need to use in different places. The issue is some places i need to pass function without parameters and some places with parameters to call back function. How can i handle in both the scenarios.
function deletePrompt(message, callback){
$("#deleteModelWindow").modal({
containerCss: {
width: 320,
height: 180,
overflow: 'hidden'},
onShow: function(dialog){ dialog.wrap.css('overflow','hidden'); }
});
document.getElementById("spanid").innerHTML = message;
$("#deleteModelWindow").on('click', "#deleteConfirm", function(){
if (callback !== undefined) {
callback();
} else {
callback(parameter1,parameter2);
}
$.modal.close();
});
$("#deleteModelWindow").on('click', "#cancel", function(){
$.modal.close();
});
}
calling From:
<input id="deleteInvitationBtn" class="buOrange large" type="button" name="submit" value="Delete Invitation" onClick="deletePrompt('Are you sure you want to delete the invitation?', deleteInvitation('${invitation.invitationId}','${invitation.clientActivationCode}'))">
Here, In onclick before it redirects to deletePrompt() it is directly redirecting to the deleteInvitation().
Can anyone explain why this is happening?
Upvotes: 1
Views: 103
Reputation: 70718
You can use arguments
object or check if message
and callback
are undefined:
function deletePrompt(message, callback) {
$("#deleteModelWindow").modal({
containerCss: {
width: 320,
height: 180,
overflow: 'hidden'},
onShow: function(dialog){ dialog.wrap.css('overflow','hidden'); }
});
if (message !== undefined) {
document.getElementById("spanid").innerHTML = message;
}
if (callback !== undefined) {
$("#deleteModelWindow").on('click', "#deleteConfirm", function() {
callback();
callback(parameter1,parameter2);
$.modal.close();
});
}
$("#deleteModelWindow").on('click', "#cancel", function(){
$.modal.close();
});
}
JSFiddle demonstrating the concept: http://jsfiddle.net/on3b7sv4/
It may also be better to split the binding logic up into smaller functions so the function is cleaner.
Upvotes: 1
Reputation: 1073968
That's fine. JavaScript functions are really flexible, you can pass them more arguments than they expect, or fewer; within the function, any declared argument that you don't pass will have the value undefined
. Any undeclared argument you pass will be available as part of the arguments
pseudo-array.
Example:
function test(label, a, b) {
var n;
snippet.log("------- " + label);
snippet.log("a = " + a);
snippet.log("c = " + b);
if (arguments.length > 3) {
snippet.log("Extra arguments:");
for (n = 3; n < arguments.length; ++n) {
snippet.log("#" + n + ": " + arguments[n]);
}
}
}
test("test1", 1, 2);
test("test2", 1);
test("test3");
test("test4", 1, 2, 3, 4);
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="//tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
Upvotes: 0