Server Events JS/TS client addListener losing 'this'

I’m using Ionic and on a view load I’m trying to add a listener, and on a view unload I’m trying to remove a listener.

  ionViewDidLoad()
  {
    this.serverEvents.client.addListener("ProductDetailsChanged", this.productDetailsChangedHandler);
  }

  ionViewWillLeave()
  {
    this.serverEvents.client.removeListener("ProductDetailsChanged", this.productDetailsChangedHandler);
  }

The problem is, ‘this’ gets lost in my handler. I could wrap the function and return a closure with a var that = this; kind of hack, but then I can’t use removeListener properly because that’ll be two different functions/objects.

Any thoughts on what I can do?

Here’s my handler:

private productDetailsChangedHandler(msg)
  {
      console.log("productDetailsChangedHandler", msg);

      let evt = JSON.parse(msg.json);
      console.log("evt", evt);
      console.log("product", this);

      //if(evt.productId == this.product.productId)
      //{
      //  console.log("updating product", msg, evt);
      //  this.product = angular.merge(this.product, evt.details);
      //}
  }

The log with ‘this’ in it returns undefined.

This is how JavaScript works, i.e. if a Function isn’t bound, this is always the call site of the object the method it’s called on, e.g:

obj.method(); //this = obj
bar.method = obj.method;
bar.method(); //this = bar

If it’s not called on an object, then this is undefined, e.g:

var fn = obj.method;
fn(); //this = undefined

You can use .bind() to bind a function to a method in JavaScript, e.g:

var fn = this.productDetailsChangedHandler.bind(this);
fn(); //this = this

The real issue I was having was how to unbind it. If I addListener(this.fn.bind(this)) then removeListener(this.fn.bind(this)) wouldn’t work because it wraps/scopes the method.

But I was being dense. Your example presented gave me the answer I needed. I can set a variable to my bound version of the method and then unbind with that same variable. var fn = this.classFn.bind(this); addListener(fn); removeListener(fn);

Thanks for the reply!