EDIT: I've made a few changes to re-clarify the issue I'm having.
I have a simple Javascript plugin that I want to add some callback features to as part of its default functionality. Users would be able to specify a function to be called when a certain button is clicked on.
// Define option defaults
var defaults = {
//some other defaults
onOK: null, //callback functions to be specified here (exists as string)
onClose: null //callback functions to be specified here (exists as string)
}
Normally, this works fine when there's a simple function with no arguments. The option is passed to here:
function initializeEvents() {
//If a close button event is clicked, run this.
if (this.closeButton) {
this.closeButton.addEventListener('click', this.close.bind(this)); //Bind close event to the button
this.closeButton.addEventListener('click', window[this.options.onClose]); //passed to here
}
//If an OK button event is clicked, run this.
if (this.okButton) {
this.okButton.addEventListener('click', this.close.bind(this));
this.okButton.addEventListener('click', window[this.options.onOK]); //passed to here
}
}
window[]
is supposed to become a function call to the appropriate button. It has come to my attention that I should NOT be using window[]
.
EDIT: However, as @adeneo pointed out, I'm making a BIG mistake here by adding my functions as strings, which simply results in the function becoming undefined
instead when I have to add it to an event listener.
I've tried using an anonymous function, but I'm still not getting the function to work:
var callbackModal = new raModal({
content: '<div>You clicked on the Callback button. This shows the popup, but has a custom callback function, called when the user clicks OK and/or Close.</div>',
onOK:{function(){
okCallback('4');
}
},
onClose: "closeCallback",
closeButtonText: "Close"
});
callbackModal.open();
So, my question has changed to: How can I properly add my anonymous functions from the defaults?
Link to a JSFiddle that reproduces the issue. You'll notice that while the Close button works as intended (with closeCallback
printing the console.log message), the OK button calling okCallback(num)
does nothing.
Any help is greatly appreciated.