edg edg - 7 months ago 10
Javascript Question

How can I execute a function passed as an option in a Jquery plugin?

I'm creating a plugin that add buttons based on the options passed into it. I can already render the buttons but I can't figure out how to execute the function when the button is clicked.

Here's an example of how the plugin is used:

$("#myobj").myPlugin({
width: 100,
height: 100,
buttons: {
"Say Hello": function () { alert("Hello World!"); },
"Goodbye": function() { alert("Goodbye!"); },
"Other": function() { alert("Something here"); }
}
});


I'm trying something like the below inside the plugin source code but I couldn't make the function call work on button click. Please help...

if (options.buttons !== null) {
var buttons = "";
for (var property in options.buttons) {
//console.log(property + ': ' + options.buttons[property]);
buttons += "<button onclick='" + options.buttons[property] + "'>" + property + "</button>"
}
}

Answer

I would suggest adding a "data" attribute with the property name and always call the same method onClick.

buttons += "<button data-property='" + property + "'>" + property + "</button>";

...

$("#myobj").on("click", "button", function(){
    var matchingButtonPropName = $(this).data("property");
    options.buttons[matchingButtonPropName].call(this);
});