Passing Parameters into JavaScript object events using jQuery
I know there are a LOT of similar question to this, but I've tried them all to no avail...so thanks for any help.
WHAT I AM TRYING TO DO: I want to pass one-to-many parameters into each checkboxes 'click' event upon registration (see below).
WHAT WORKS: I can register the event WITHOUT any parameters, and the click event raises...but I need to pass-in a reference to the containing JavaScript grid object (for other reasons开发者_JAVA百科).
WHAT FAILS I've tried various forms of "this.MutuallyExclusiveCheckBoxHandler = function(grid){}" to no avail.
ONE IDEA: I "think" currying may be the answer, but I don't quite know how to do it well-enough (yet).
This area instantiates the grid and registers the checkboxes
<script type="text/javascript">
<!--
// CLASS
function CommitImporterGrid() {
// PROPERTIES
this.Toaster = new Toaster();
this.CheckBoxes = new Array();
// METHODS
this.RegisterMutuallyExclusiveCheckBox = function(clientId) {
var checkBox = $j('input:checkbox#' + clientId);
// HERE: "I need to pass a reference to the grid somehow"
$j(checkBox).click(this.MutuallyExclusiveCheckBoxHandler);
this.CheckBoxes.push(checkBox); // Append to array
}
this.MutuallyExclusiveCheckBoxHandler = function() {
// The checkbox events break when I try to add a parameter.
var myGrid = "I need to retreive the grid reference here somehow";
if (!$j(this).is(':checked')) { // They clicked on the same checkbox
this.checked = true;
return;
}
// ...other code...
}
}
// CLASS INSTANCE
var myGrid = new CommitImporterGrid();
// DOM EVENT: Document.Ready()
$j(document).ready(function() {
// DYNAMIC REGISTRATION
myGrid.RegisterMutuallyExclusiveCheckBox('chkCommitImporter01');
myGrid.RegisterMutuallyExclusiveCheckBox('chkCommitImporter02');
});
-->
</script>
Use .bind()
and pass event data (assuming your grid is the current object):
// HERE: "I need to pass a reference to the grid somehow"
checkBox.bind('click', {grid: this}, this.MutuallyExclusiveCheckBoxHandler);
(you don't need to pass checkbox
to jQuery, it is already a jQuery object)
and change your method to:
this.MutuallyExclusiveCheckBoxHandler = function(event) {
var mygrid = event.data.grid;
//...
}
(You can can access the event data via event.data
)
You need to add an anonymous function that calls your handler with your parameters, like this:
this.RegisterMutuallyExclusiveCheckBox = function(clientId) {
var self = this;
var checkBox = $j('input:checkbox#' + clientId);
$j(checkBox).click(function() {
self.MutuallyExclusiveCheckBoxHandler(parameters);
});
this.CheckBoxes.push(checkBox); // Append to array
};
Inside the event handler, this
refers to the element that triggered the event.
I therefore use a separate self
variable instead.
精彩评论