【问题标题】:Detect when document is closed检测文档何时关闭
【发布时间】:2018-02-08 19:50:10
【问题描述】:

我正在开发 Visual Studio Code 扩展,我需要检测某个文档窗口何时关闭。 我知道 vscode.workspace.onDidCloseTextDocument 事件,它一般都有效。

但如果我通过 API 从工作区打开一个文件:

vscode.workspace.openTextDocument(localPath).then(function (doc) {
    vscode.window.showTextDocument(doc, 1);
});

然后关闭它,onDidCloseTextDocument 不会像往常一样触发。 它着火了,但几分钟后。

我知道这是一些错误还是 VSCode 的工作方式,但我需要知道如何检测文档窗口何时关闭。

我通过 API 读取的打开文件是某种“虚拟”文件。所以,这可能是导致问题的原因。

【问题讨论】:

  • 当您通过 API 关闭 TextDocument 时,您是否检查过 TextDocument.isClosed 属性是否更新?
  • 是的,我试过了,但即使文件关闭,它也会返回“false”。同样,该错误仅在通过 API 加载文档时出现。当通过 UI 打开文档时 isClosed 返回真实状态。
  • 尚未使用工作区文档,但它们会在关闭之前触发 DocumentClosing 事件吗?你可能会在那个事件中做一些魔法,即使你并不是真的打算这样使用它。如果您自己控制关闭,也许您可​​以依靠检查文件是否打开(物理上)或其他一些技巧?
  • 会不会是因为文档说Note that the lifecycle of the returned document is owned by the editor and not by the extension. That means an onDidClose-event can occur at any time after opening it.

标签: javascript visual-studio-code vscode-extensions


【解决方案1】:

‍‍vscode.workspace.onDidCloseTextDocumentdisposed 文本文档时发出。要在可见文本文档关闭时添加事件侦听器,请使用窗口命名空间中的TextEditor 事件。请注意,当 TextEditor 关闭但文档在另一个可见的文本编辑器中保持打开状态时,不会发出此事件。

更多信息请见this

【讨论】:

    【解决方案2】:
    private _subscriptions: vscode.Disposable;
    
    constructor() {
    
        // Listen to closeTextDocument
        this._subscriptions = vscode.workspace.onDidCloseTextDocument(
            // your code here
        );
    }
    
    dispose() {
        this._subscriptions.dispose();
    }
    

    【讨论】:

      【解决方案3】:

      遗憾的是,没有办法让文件关闭 atm,因为信不信由你onDidCloseTextDocument 触发不仅仅是关闭文件,测试将以下内容添加到您的分机 active

      vscode.workspace.onDidCloseTextDocument((doc) => {
          console.log(doc)
      })
      

      并在控制台中观看魔术。

      除了完全不相关的文档

      要在可见文本文档关闭时添加事件侦听器,

      使用窗口命名空间中的 TextEditor 事件。

      window 命名空间https://code.visualstudio.com/api/references/vscode-api#window 上没有关闭事件可能是盲人,但如果有人发现它,请在此处添加。

      文档上的isClosed 属性也不可靠,因为打开文档时它实际上是true

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-11-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多