Reputation: 24602
I have the following:
var oTable = $('#dataTable').dataTable({
iDisplayLength: -1,
...
...
$("#dataTable tbody").on("click", "tr", gridClickHandler);
function gridClickHandler(oTable) {
$(oTable.fnSettings().aoData).each(function () {
$(this.nTr).removeClass('row_selected');
});
$(this).addClass('row_selected');
I was told that the $(this) event will be passed to the function but I need to also pass something else as I found it gives an error relating to oTable.
How can I modify my call to gridClickHandler and the gridClickHandler function so it passes a reference to oTable and also so the $(this) works.
Upvotes: 0
Views: 97
Reputation: 694
Try this:
$("#dataTable tbody").on("click", "tr", gridClickHandler);
gridClickHandler.oTable = oTable;
function gridClickHandler(event) {
$(oTable.fnSettings().aoData).each(function () {
$(this.nTr).removeClass('row_selected');
});
$(event.target).addClass('row_selected');
}
Upvotes: 0
Reputation: 186103
If the variable oTable
is declared in an outer scope, the gridClickHandler
function will have access to it, so you don't need to pass it manually. As a matter of fact, event handlers receive the event object as the first argument, so you're actually shadowing the TABLE reference.
For example:
var foo = 123;
var clickHandler = function ( foo ) {
// here, foo is not 123, but the event object
// the outer variable foo is shadowed by the local variable foo
};
Just remove the first argument:
var gridClickHandler = function () {
Now, oTable
is retrieved from the outer scope.
(Also notice, how I assign a anonymous function expression to a variable, instead of using a function declaration.)
Btw, inside the function, this
refers to the TR element.
Upvotes: 1
Reputation: 31097
You could use an anonymous function:
$("#dataTable tbody").on("click", "tr", function(event) { gridClickHandler(oTable); } );
Upvotes: 1