Reputation: 7012
I am very new to jQuery world, sorry if this is too basic a question. I have a jQuery function to create button dynamically:
function createButton(element, id, caption, leftPosition) {
if (element == null || element.length < 1) return;
var buttonTable = $("<table id='" + id + "'>");
buttonTable.addClass("togglebtn");
buttonTable.css("left", left);
var trow = $("<tr>");
$("<td>")
.text(cellText)
.data("buttonname", caption)
.click(function () {
//alert("Clicked Col=" + $(this).data("buttonname"));
TestButtonClick();
})
.appendTo(trow);
trow.appendTo(buttonTable);
buttonTable.appendTo(element);
}
Since this is a general method to create buttons, I want to add a click event to it so that the calling program can execute it's own method on click event. I mean I want to pass the client method name as parameter to createButton method which should eventually execute it on click. How is it possible to do and how to call the createButton method with that parameter?
Upvotes: 0
Views: 4708
Reputation: 4471
Looks like I read a little too far into your question. I thought you also wanted to pass a parameter to the event handler. My answer still works, it just does a little bit extra.
You can use the call
method to call another method with certain parameters. You can also pass a function into another function as a parameter. Something like this:
function createButton(element, id, caption, leftPosition, clickHandler) {
// your stuff
.click(function() {
clickHandler.call(this, yourParam);
})
// the rest of your stuff
}
function onClick(aParam) {
console.log(this);
console.log(aParam);
}
createButton($("<element/>"), "id", "caption", "leftPos", onClick);
Here's a fiddle for an example.
Upvotes: 1
Reputation: 7012
Sorry it was really a very stupid of me to post this question without trying enough. I got the answer. Here is what I did:
function createButton(element, id, caption, leftPosition, callbackfunction) {
//do something
callbackfunction();
}
Calling program:
createButton($("#tbl"), "btnSave", "Save", "100px", function () { TestButtonClick() });
Upvotes: 3