Reputation: 1625
I have the following simplified function:
public constructPoints() {
mapArray.push("hello");
}
I'm calling the function from two spots:
protected onDataSourceLoaded() {
this.constructPoints();
}
AND
public OnSourceChanged(source) {
this.pageSource = source;
//this.onDataSourceLoaded();
this.constructPoints();
}
In the same file, I have this code block where OnSourceChanged is referenced:
const sourceNavContext:SourceNavContext = {
Items: this.sourceNavItems,
Context: this.fieldFormContext,
onRecordChanged: this.OnSourceChanged
};
OnDataSourceLoaded is a function that's being inherited from a base class:
protected abstract onDataSourceLoaded()
//and in that base class there's also this:
private wireupDataLoadedSubscription() {
let subscription
= this.dataLoadedNotifier.subscribe(next => this.onDataSourceLoaded());
this.subscriptions.push(subscription);
}
HERE'S MY QUESTION: When I call this.constructPoints from onDataSourceLoaded, it does what it's supposed to do. When I call it from OnSourceChanged, I get the following error: TypeError: this.constructPoints is not a function
I don't understand why I'm getting this error. Can someone point me in the right direction? As you can see, I've commented out a line in the last code snippet where this.onDataSourceLoaded is called. If I uncomment this line, I get the same error but for this function.
Upvotes: 0
Views: 652
Reputation: 250336
The problem is that you pass the function to someone else and they call it without passing you the this
parameter you expect. Try using an arrow function to capturethis
const sourceNavContext:SourceNavContext = {
Items: this.sourceNavItems,
Context: this.fieldFormContext,
onRecordChanged: s => this.OnSourceChanged (s)
};
In JavaScript this
is determined by the caller not by where the function is declared. See here and here for more
Upvotes: 1