I am creating a jquery plugin to attach events and event handlers at run time:
The HTML:
<table id="digitalInputsTable">
<thead>
<th>Name</th>
<th>Value</th>
<th>State</th>
<th>Enabled</th>
<th>Polarity</th>
<th>Ignore Reset</th>
</thead>
<tbody>
<tr>
<td>
<span class="">Name1</span>
</td>
<td>
<span class="">0</span>
</td>
<td>
<span class="">Normal</span>
</td>
<td>
<input type="checkbox" value="true" class="" jqmon="0" jqreg="0" id="digitalInputsTable_checkbox_03">
</td>
<td>
<select class="" jqmon="0" jqreg="0" id="digitalInputsTable_select_04">
<option value="0=Alarm">0=Alarm</option>
<option value="1=Alarm">1=Alarm</option>
</select>
</td>
<td>
<input type="checkbox" value="true" class="" jqmon="0" jqreg="0" id="digitalInputsTable_checkbox_05">
</td>
</tr>
</tbody>
The Data Structure:
$("#digitalInputsTable").bindEvents({
parentControl: "digitalInputsTable",
controls: [
{
id: undefined,
name: "checkbox",
idStartsWith: "digitalInputsTable_checkbox_",
event: "click",
callbackHandler: "checkboxCallback"
},
{
id: undefined,
name: "checkbox",
idStartsWith: "digitalInputsTable_checkbox_",
event: "blur",
callbackHandler: "blurCallback"
},
{
id: undefined,
name: "select",
idStartsWith: "digitalInputsTable_select_",
event: "change",
callbackHandler: "selectCallback"
}
]
});
The Plugin:
$.fn.bindEvents = function(options) {
for(var i = 0; i < options.controls.length; i++) {
var control = options.controls[i];
switch(control.name) {
case "checkbox":
control.name = ":checkbox";
break;
}
if(control.id) {
// find control by ID.
// Attach event to the control.
}
else if(control.idStartsWith) {
$("#" + options.parentControl).find(control.name + "[id^=" + control.idStartsWith + "]")
.bind(control.event, function(e) {
function(ctrl) {
eval(ctrl.callbackHandler + "();");
};
}(control));
}
};
};
The Problem:
When I check the check box, I am not able to call the “checkboxCallback” callback function of the check box. May be I am using closure incorrectly. Please advise.
This is not a complete answer, but it should point you in the right direction. Basically when you loop over the
options.controlsand need to perform actions on them in the future, you need to use a closure to separate them.Btw, don’t use
evalto call the callback, just pass the function reference:I’ve added example of how to call it inside the
$.fn.bindEventsfunction.