1

I'm making a webpage with JavaScript and jQuery. I have a checkbox with id "show-hidden-tables", and the following snippet of code to attach a click handler to it.

$('#show-hidden-tables').click(this.togglePrivateRows_);

Here is the function that is called:

togglePrivateRows_: function() {
  $('td[data-header="Private"]').each(function(index, elem) {
      if ($(this).text() === 'true') $(this).closest('tr').toggle();
  });
}

This works fine. However, if I change the click handler to this:

$('#show-hidden-tables').click(function(ev) { this.togglePrivateRows_(); }) ;

it no longer works. Why is this? What if I needed to use the ev argument in my function?

gardenhead
  • 2,299
  • 2
  • 19
  • 17

1 Answers1

2

You need to bind your function to the scope like this:

$('#show-hidden-tables').click(function(ev) {
    this.togglePrivateRows_();
}.bind(this));

And for your second question "What if I needed to use the ev argument in my function?"

Even in your first approach, the ev parameter will be pass as an argument to your this.togglePrivateRows_ function

udidu
  • 8,269
  • 6
  • 48
  • 68