Floriane Floriane - 5 months ago 16
TypeScript Question

Save old parameter in function

I create an instant messenger. My function cliked(thread) allows me to click on a discussion and view this discussion. The user can not have more than 2 chat windows open at the same time.
So when two chat windows are open (this.threadService.windows.length === 2), I have to close the first window to display the new window.

I must then save this first window in a variable, in order to enter it as a parameter of my function closeOldThread(oldThread)

clicked(thread: Thread): void {
this.newWindow = true;

let oldThread: Thread;
if(this.threadService.windows.length === 2) {
this.closeOldThread(oldThread);
}
if (!this.thread.isOpen) {
thread = this.chatService.openThread(thread);
this.chatService.setCurrentThread(thread);
this.thread.isOpen = true;
}
oldThread = thread;
}


////

closeOldThread(thread: Thread): void {
let index = this.threadService.windows.indexOf(thread);
this.threadService.windows.splice(index, 1);
this.thread.isOpen = false;
this.newUser = false;
this.newWindow = false;
}


Is that possible?
Because in my case, oldThread is undefined.

Answer Source
clicked(thread: Thread): void {
    this.newWindow = true;
    if(this.threadService.windows.length === 2) {
        // get the previously opened chat window
       let oldThread = this.threadService.windows[0];            
       this.closeOldThread(oldThread);
    }
    if (!this.thread.isOpen) {
       thread = this.chatService.openThread(thread);
       this.chatService.setCurrentThread(thread);
       this.thread.isOpen = true;
    }
}