簡體   English   中英

在打字稿中,如何創建添加裝飾器的裝飾器?

[英]In typescript how to you create a decorator that adds a decorator?

在Angular中,我嘗試在使用臟表單關閉窗口時提示用戶。 我有可以通過監聽window:beforeunload的代碼,但是在每個Component上都重復了相同的代碼。 我試圖添加一個裝飾器,該裝飾器可以放置在將混合所需邏輯的組件上,但這需要添加一個函數,然后在其上應用裝飾器。 我的嘗試在下面,但是似乎沒有用(即,從未調用我的事件監聽器)。

export function createOnBeforeUnload() {
    return function ($event: any) {
        console.log('calling onBeforeUnload', this, $event);
        if (this.isDirty && this.isDirty()) {
            console.log('setting message');
            $event.returnValue = DIRTY_CONFIRM_MSG;
        }
    };
}


export function DirtyChecking() {
    return function (target: any) {
        if (target.prototype) {
            console.log('adding dirty checking to', target);
            target.prototype._onBeforeUnload = createOnBeforeUnload();
            // attempt at adding the @HostListener decorator
            HostListener('window:beforeunload', ['$event'])(target.prototype._onBeforeUnload);
        }
    };
}

我的組件是

@DirtyChecking()
@Component({
    template: `
    <h2>Dirty Checker</h2>

    <form novalidate>

      <div class="form-group">
        <label for="dirty">Dirty?</label>
        <input class="form-control" type="checkbox" id="dirty" name="dirty"
               [(ngModel)]="dirty">
      </div>

    </form>
  `,
})
export class DemoDirtyCheckerComponent implements IsDirty {

    private dirty = false;

    constructor() {
    }

    toggle() {
        this.dirty = !this.dirty;
    }

    isDirty() {
        console.log('is dirty demo?', this.dirty);
        return this.dirty;
    }
}

之所以調用裝飾器,是因為我在控制台中看到“向其添加臟檢查”。 但是,當我關閉窗口時, _onBeforeUnload不會像我期望的那樣被調用。

我接受了@Harry Ninh提出的解決方案

import { HostListener } from '@angular/core';

export abstract class IsDirtyComponent {
    abstract isDirty(): boolean;

    @HostListener('window:beforeunload', ['$event'])
    onBeforeUnload($event: any): void {

        if (this.isDirty()) {
            $event.returnValue = 'Are you sure?';
        }
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM