Reputation: 393
The directive below registers a listener with MessageBus class. Which executes the registered callback when the dispatch function is called. I need to access the "dragZoneElems" from within the callback and perform operations on it. Please advice on how to do this. At present it says dropZoneElems = undefined, since this data is outside the callback scope. However the data is present and is not undefined.
export class DragZoneDirective implements OnInit{
private _messageBus : IMessageBus
@Input() dragZoneElems: Object[];
constructor() {
this._messageBus = MessageBus;
}
ngOnInit(){
this._messageBus.listen("dragStart", function(val) {
console.log("DragStart", this.dragZoneElems);
let index = this.dragZoneElems.indexOf(val);
if(index > -1)
this.dragZoneElems.slice(index, 1);
});
this._messageBus.listen("dragStop", function(val) { console.log("DragStop"); });
}
}
Message Bus-
static dispatch(event: string, info?: any): void {
this.listeners
.forEach((l) => {
if (l["event"] === event) {
l["cb"](info);
}
});
}
Upvotes: 1
Views: 763
Reputation: 202196
You need to use arrow functions to be able to use the lexical this (it corresponds to your component instance):
this._messageBus.listen("dragStart", (val) => { // <--------
console.log("DragStart", this.dragZoneElems);
let index = this.dragZoneElems.indexOf(val);
if(index > -1)
this.dragZoneElems.slice(index, 1);
});
See this link for more hints about the lexical this of arrow functions:
Upvotes: 5