2

I need to show a block when the button is clicked, so I do this :

var container = $('#container');

$('button').on('click', container.show);

and it doesn't work, however, when I write this, it works :

var container = $('#container');

$('button').on('click', function() {
    container.show()
});

Can somebody explain me why the first version doesn't work ? Is there a way to use show method without writing an anonymous function in the event handler ?

Tomas.R
  • 715
  • 2
  • 7
  • 18
  • Did you try passing `container.show()` (with parenthesis and no parameters)? – Coda17 May 23 '14 at 16:21
  • 2
    @Coda17 that will invoke show immediately. – Matas Vaitkevicius May 23 '14 at 16:22
  • You need to pass it a function expression/declaration which it can then execute later, when the 'click' event occurs. So if you execute it immediately with `container.show()` it will error. – iLikePrograms May 23 '14 at 16:23
  • @LIFUA I just tested and you are absolutely correct. Should I delete my comment or leave it there so yours doesn't look silly by itself? – Coda17 May 23 '14 at 16:27

1 Answers1

0

I could be wrong, but you may be able to do this:

var container = $('#container');

$('button').on('click', container.show.bind(container), false);

The bind method should itself create an anonymous function, which is what the second paramater of .on should expect.

See here for the MDN article on Function.prototype.bind

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

iLikePrograms
  • 470
  • 2
  • 9
  • Nope, it doesn't work. However, console window in developer tools doesn't log any errors either. You know what, this whole thing is not very important to me at this point, so I think we should call it quits, I feel like I'm wasting your time which could be used for better purposes. Thank you and good luck. – Tomas.R May 24 '14 at 08:59
  • Nah your not wasting my time. Try assigning container.bind() to a variable first, then passing the variable to the on click. You could also try passing null into bind after that, who knows jQuery might not like it setting the context to a jQuery expression? – iLikePrograms May 24 '14 at 09:07