In this particular scenario, I am looking to substitute the variable that was sent...
Unfortunately, you cannot achieve this directly. The parameter you have is not linked to the variable used as a function argument in any way (JavaScript operates on pass-by-value for strings, rather than pass-by-reference where a reference to the variable is passed into a function).
If your aim is simply to set the values of those observables, you can proceed as follows:
if (itemFound) {
observable1(item.observableX());
observable2(item.observableY());
}
Alternatively, you could subscribe to the new observables, although this may result in numerous subscriptions:
// This approach may not be ideal
if (itemFound) {
item.observableX.subscribe(observable1);
item.observableY.subscribe(observable2);
}
...however, if your intention is indeed to replace the observables themselves, it may be preferable for `searchAndReplace` to actually return the pair of observables meant to replace the current ones:
private searchAndReplace = (flag: string, observable1: KnockoutObservable<string>, observable2: KnockoutObservable<string>) => {
const itemFound = this.items.find((item) => item.flag === flag);
if (itemFound) {
return [item.observableX, item.observableY];
}
return [observable1, observable2];
}
Then, when calling it, utilize destructuring assignment like so:
[original1, original2] = searchAndReplace("flag", original1, original2);