打字稿-吸气剂和吸气剂:调用吸气剂时检测对象变化

时间:2018-06-27 14:19:18

标签: angular typescript

我有以下课程:

@Injectable()
export class ViewCacheService{

    private key: string = "cache";
    private prefix: string = "view";

    private get viewFifoStack() {
        let _viewFifoStack: ViewCacheFifoStack = this._clientCacheService.getFromCache(this.key, this.prefix) as ViewCacheFifoStack;
        if(!_viewFifoStack) _viewFifoStack = new ViewCacheFifoStack();
        return _viewFifoStack;

    }

    private set viewFifoStack(viewFifoStack: ViewCacheFifoStack) {
        if(viewFifoStack)
            this._clientCacheService.setToCache(this.key, this.prefix, this.viewFifoStack);
    }

    constructor(private _clientCacheService: ClientCacheService) {}

    setFocusElement(element: HTMLElement) : void {
        let node: ViewCache = this.viewFifoStack.getNode(true);
        if(!node) node = new ViewCache();
        node.focusElement = element;
        this.viewFifoStack.addNode(node);
    }
}

此类作为名为viewFifoStack的属性,具有一个setter和一个getter。问题是,当我调用方法setFocusElement并执行this.viewFifoStack.addNode(node)时,不会调用setter函数。

我知道这种行为是正确的,应该可以那样工作。我正在寻找的是一种在ViewFifoStack的堆栈私有属性发生更改时调用setter的方法。

遵循ViewCacheFifoStackViewCache类:

class ViewCacheFifoStack{
    private stack: Array<ViewCache> = new Array<ViewCache>();
    constructor() {}

    getNode(remove: boolean = true): ViewCache | null{
        if(remove) this.removeLast();
        if(this.stack.length > 0) 
            return this.stack[this.stack.length - 1];
        return null;
    }

    addNode(viewCache: ViewCache): void {
        if(viewCache)
            this.stack.push(viewCache);
    }

    private removeLast(): boolean{
        if(this.stack.length > 0){
            this.stack.pop();
            return true;
        }
        return false;
    }
}

class ViewCache {
    focusElement: Element;
}

0 个答案:

没有答案