Ionic 2: Events publish/subscribe loses context
See original GitHub issueShort description of the problem:
When subscribing to an Event, providing inline code preserves context, but providing a function loses context.
Given a class function like this:
setFlag() { /* do some stuff here */ }
This works:
this.events.subscribe('hello', ()=>{ this.setFlag(); });
But this fails, with no such function setFlag:
this.events.subscribe('hello', this.setFlag );
In another component:
this.events.publish('hello');
This is problematic, because there’s no way to unsubscribe from inline code.
What behavior are you expecting?
I would expect the context to be preserved in the message handler.
Which Ionic Version? 1.x or 2.x
2 beta 11
Run ionic info
from terminal/cmd prompt: (paste output below)
Cordova CLI: 6.3.0 Gulp version: CLI version 3.9.0 Gulp local: Local version 3.9.1 Ionic Framework Version: 2.0.0-beta.11 Ionic CLI Version: 2.0.0-beta.36 Ionic App Lib Version: 2.0.0-beta.19 ios-deploy version: 1.8.3 ios-sim version: 5.0.4 OS: Mac OS X El Capitan Node Version: v4.2.2 Xcode version: Xcode 7.3.1 Build version 7D1014
Issue Analytics
- State:
- Created 7 years ago
- Comments:8 (3 by maintainers)
@thomaswb Using publish/subscribe u have to explicitly bind context or use arrow function like this
I believe your issue simply boils down to how
this
is handled in JavaScript, so hopefully the following explanation will help:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this