Reputation: 5223
I have read the relative questions here which they propose to use something like:
var functionName="myFunctionName";
window[functionName]();
Well here i am but it doesn't work:
Custom modal box function that has a callback string variable:
<script>
$(document).ready(function () {
//
// Events
//
$('#btnStep1').click(function () {
ylaConfirm('message', 'title', 'Y', 'N', 'doStep1');
});
//
//
// Functions
//
function doStep1() {
...
...
});
}
function ylaConfirm(_msg, _title, _btnYes, _btnNo, _callbackYes) {
bootbox.dialog({
message: _msg,
title: _title,
buttons: {
success: {
label: _btnYes,
className: "btn-success",
callback: function () {
window[_callbackYes]();
}
},
main: {
label: _btnNo,
className: "btn-primary"
}
}
});
}
});
//
</script>
Firebug reports: not defined...
Calling Code:
ylaConfirm('message', 'title', 'Y', 'N', 'doStep1');
ideas?
Upvotes: 1
Views: 2721
Reputation: 107
I would say the call
window[_callbackYes]();
is completely ok. The problem is the scope of doStep1()
. Defined inside the anonymous ready function, it is not attached to the window object and only callable inside the outer function. Further reference can be found here: Functions and Function scope
My suggestion: Either define doStep1()
outside the ready function or attach it to the window object like this:
window.doStep1 = function() {
//do stuff
}
This could be necessary if you need the page to be initialized for the function definition (which is highly unlikely I think)
Upvotes: 1
Reputation: 239463
Three things.
ylaConfirm('message', 'title', 'Y', 'N', 'doStep1');
window[_callbackYes]();
is executed, doStep1
is not yet defined. So you can define it before click
function.The other way to fix this problem is to defined doStep1
as an inline anonymous function and calling it directly as _callbackYes()
instead of window[_callbackYes]();
. So, ylaConfirm
call will become like this
ylaConfirm('message', 'title', 'Y', 'N', function(){
//Include the actual definition of doStep1 here.
});
As mentioned by @VoronoiPotato in the comments, you can pass the function directly as the third parameter (either you should move the definition of doStep1
before click
or define doStep1
like this var doStep1 = function() {..}
).
ylaConfirm('message', 'title', 'Y', 'N', doStep1);
...
...
_callbackYes(); // Instead of window[_callbackYes]();
Upvotes: 3
Reputation: 15893
What you describe indicates that window[_callbackYes]
is not defined during the execution of ylaConfirm
, but is defined by the time the Yes
button is clicked.
Move definition of doStep1
function doStep1() {
...
}
before
$(document).ready(function () {
...
}
Upvotes: 2