Tom
Tom

Reputation: 1057

Remove an event handler from the child of a bound element

I have click handlers I want to apply to the rows in my table:

var myTable = $(this);
myTable.on('expand', 'tr', myHandler);
myTable.on('click', 'tr', function () {
    $(this).trigger('expand');
});

function myHandler(e) {
    // my action
}

This is a much simplified version, but it fires a jQuery method that expands the rows. I want to remove this handler from particular rows depending on their contents. I have a function that is fired every time the row is clicked. If it does not match set conditions, a method is fired displaying a message informing the user of the issue. I want to now disable the click to expand of this row.

function stopFunction(row) {
    row.find('th[scope=row]').parents("#tableID").off('expand', 'tr', myHandler);
}

The above just removes the click to expand capabilities from all rows. I don't know how to go about allowing the clicking of other rows, but just removing the handler from this single table row. Please note, the row.find('th[scope]') is the table cell of the row, the first parent of that is it's row, and then the row's parent is the table (@tableID).

Upvotes: 2

Views: 140

Answers (2)

Linus Thiel
Linus Thiel

Reputation: 39231

As you have found out, your .off call will turn off the whole event handler. That's because, using on (which is a good practice), you only have one event handler, which responds to all matching elements (tr in your case).

I suggest you do this using classes instead. Adding a class no-expand to those trs which shouldn't expand, and using this event handler instead:

myTable.on('click', 'tr:not(".no-expand")', function() { ... })

function stopFunction(row) {
  row.addClass("no-expand");
}

Upvotes: 1

karim79
karim79

Reputation: 342655

function stopFunction(row) {
    row.on("click", function (e) {
        e.stopPropagation();
    });
}

Proof of concept.

Upvotes: 2

Related Questions