簡體   English   中英

如何存儲異步回調函數的變量

[英]How to store the variable of an asynchronous callback function

我正在開發chrome擴展程序,並嘗試在插件內textarea中的選項卡上輸出所選文本。

獲取所選文本的功能效果很好,但是我無法將值設置為插件內的textarea元素。

問題:如何正確存儲值,以便能夠通過數據綁定將其傳遞到文本區域?

HTML:

<div>
    <p>Here will appear the selected text :</p>
    <textarea name="selectedText" id="selectedText" [(ngModel)]="selectedText"></textarea>
    <button (click)="getSelectedText()">Get the selected text</button>
</div>

TS:

export class CaptureComponent {
    selectedText = '';

    getSelectedText() {
        chrome.tabs.executeScript( {
            code: 'window.getSelection().toString();'
        }, function(selection) {
            this.selectedText = selection[0];
        });
    }
}

selection[0]正常工作,所以我想我嘗試存儲數據的方式不正確,但是我似乎找不到要更改的內容。

在您當前的方法中, this並不涉及您的組件。

更改您的回調以使用箭頭功能保持范圍:

getSelectedText() {
   chrome.tabs.executeScript( {
     code: 'window.getSelection().toString();'
     }, (selection) => {
       this.selectedText = selection[0];
    });
}

暫無
暫無

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

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