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.
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:
let evt = JSON.parse(msg.json);
//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 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
var fn = obj.method;
fn(); //this = undefined
You can use
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!