2

I have a listener like this one :

this.frame.on('touchend', self.findClosestSlide);

I need to have it like this, instead of inside an anonymous function in order to be able to unbind it later, using the function name.

My problem is that, once I am in the findClosestSlide function, my this object logically becomes this.frame.

How can I access the original this, or how can I have control on the context I'm sending to my callback function? (without using an anonymous function)

Romain Braun
  • 3,624
  • 4
  • 23
  • 46

2 Answers2

2

You can store this inside another variable such as that or $this than using it inside your findClosestSlide function.

Felix
  • 37,892
  • 8
  • 43
  • 55
2

You can use Function.bind() or $.proxy() to pass a custom context to a callback like

Cross Browser, use $.proxy()

this.frame.on('touchend', $.proxy(self.findClosestSlide, self));

or IE9+, use function.bind()

this.frame.on('touchend', self.findClosestSlide.bind(self));

Why? because by default this inside the event handler will refer to the element that was targeted by the event

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531