VSCode Extension Dev3

Vscode Extension (플러그인) 만들기3

저번 markdown 파일에서 업그레이드 버전입니다.
단어수 체크할 때 Hi 를 계속 호출하기 귀찮으니 자동으로 체크해주는 코드입니다.

우선 클래스를 하나 만들어 주고..

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class WordCounterController {

private _wordCounter: WordCounter;
private _disposable: Disposable;

constructor(wordCounter: WordCounter) {
this._wordCounter = wordCounter;

// subscribe to selection change and editor activation events
let subscriptions: Disposable[] = [];
window.onDidChangeTextEditorSelection(this._onEvent, this, subscriptions);
window.onDidChangeActiveTextEditor(this._onEvent, this, subscriptions);

// update the counter for the current file
// 키면 한번 업데이트
console.log('update');
this._wordCounter.updateWordCount();

// create a combined disposable from both event subscriptions
this._disposable = Disposable.from(...subscriptions);
}

dispose() {
this._disposable.dispose();
}

private _onEvent() {
console.log('_onEvent');
this._wordCounter.updateWordCount();
}
}
  • onDidChangeTextEditorSelection 함수는 커서 위치가 변경되면 이벤트가 발생
  • onDidChangeActiveTextEditor 함수는 활성 편집기가 변경되는 이벤트

파라미터

1
2
3
4
5
A function that represents an event to which you subscribe by calling it with a listener function as argument.
@param listener — The listener function will be called when the event happens.
@param thisArgs — The this-argument which will be used when calling the event listener.
@param disposables — An array to which a disposable will be added.
@return — A disposable which unsubscribes the event listener.

코드를 이해하면서 봐야하는데…

로그찍어서 확인해보니 onDidChange* 함수가 실행되면 this._onEvent 가 실행되서 updateWordCount() 가 됩니다.

이제 클래스를 만들었으니 적용해야합니다.

activate 를 수정해줍시다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
export function activate(context: ExtensionContext) {

// Use the console to output diagnostic information (console.log) and errors (console.error).
// This line of code will only be executed once when your extension is activated.
console.log('Congratulations, your extension "WordCount" is now active!');

// create a new word counter
let wordCounter = new WordCounter();
let controller = new WordCounterController(wordCounter)


// Add to a list of disposables which are disposed when this extension is deactivated.
context.subscriptions.push(wordCounter);
context.subscriptions.push(controller);

}

json 파일도 수정해줍니다. activationEvents 안에 onLanguage:markdown 설정을 해줍니다.

onLanguage:${language} 이벤트는 언어 ID 를 사용하며 해당 언어의 파일이 열리면 발생합니다.

mands 의 sayHi 는 필요없어져서 지웠습니다.

Vscode Extension 만들기1

이제 자동으로 체크해줍니다!

Vscode Extension 만들기2

참조

공유하기