Search code examples

should I bind this to the return value of jQuery on() or the handler?

I have found two ways of using Javascript's native bind as I migrate away from jQuery.proxy():

this.thing.on(event, someHandler.bind(this))


this.thing.on(event, someHandler).bind(this)

As far as I can tell, they both do the same thing, but I'm worried that the latter might cause issues in the on() (or any function in its place). The former syntax is what I'm used to from $.proxy(), and to me looks like it's explicitly binding to the handler, so I'm leaning towards using that syntax.

Are these two lines actually doing the same exact thing? And if not, which is the safer option?


  • In the first case:

    this.thing.on(event, someHandler.bind(this))

    The native bind is invoked, and it'll work as you expect.

    In the second case,

    this.thing.on(event, someHandler).bind(this)

    The jQuery on() method will return a jQuery object to which the events where bound, and when you call bind() on a jQuery object, jquery bind() method is being invoked, and it doesn't do what native bind does.