Issue
Hello I create this Typescript class to reuse my search.
export class WorkerSearch {
private loadingWorkers: Ref<boolean>;
private possibleWorkers: Ref<UnwrapRef<Array<TsadWorker>>>;
constructor(loadingWorkers: Ref<boolean>, possibleWorkers: Ref<UnwrapRef<TsadWorker[]>>) {
this.loadingWorkers = loadingWorkers;
this.possibleWorkers = possibleWorkers;
}
public workerSearch(email: string) {
console.log("worker search");
this.loadingWorkers.value = true;
const map = new Map<string, StringFilterField>();
map.set("email", StringFilterField.fromValue(email));
const searchRequest = new SearchRequest(10, 0, map);
axios
.post(process.env.VUE_APP_BACKEND_URL + "users/workers/search", searchRequest)
.then(response => {
console.log("response recieved")
this.possibleWorkers.value = response.data
this.loadingWorkers.value = false
})
.catch(error => {
defaultErrorHandler(error)
})
}
}
But when using it there is a error at the console: "error TypeError: this.loadingWorkers is undefined"
If i remove ' this.loadingWorkers = true' the error says "error TypeError: this.possibleWorkers is undefined".
How is this even possible?
This is the constructor call:
let loadingWorkers = ref(false);
let possibleWorkers = ref(new Array<TsadWorker>());
const workerSearchObj = new WorkerSearch(loadingWorkers, possibleWorkers);
Thank you for your help
Solution
Your workerSearch
method is unbound when you extract it from your WorkerSearch
instance and pass it somewhere else, that is, this
is not necessarily workerSearchObj
when not calling the method as workerSearchObj.workerSearch()
let loadingWorkers = ref(false);
let possibleWorkers = ref(new Array<TsadWorker>());
const workerSearchObj = new WorkerSearch(loadingWorkers, possibleWorkers);
// instead of
doSomethingWith(workerSearchObj.workerSearch)
// bind the value of `this` before passing the function
doSomethingWith(workerSearchObj.workerSearch.bind(workerSearchObj))
// or wrap the function
doSomethingWith(mail => workerSearchObj.workerSearch(mail))
// or bind the function from within the class constructor
export class WorkerSearch {
// ...
constructor(loadingWorkers: Ref<boolean>, possibleWorkers: Ref<UnwrapRef<TsadWorker[]>>) {
// ...
this.workerSearch = this.workerSearch.bind(this);
}
// ...
}
Answered By - DustInCompetent
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.