Angular 角度服务回调命令组合 安装程序
我一直在开发一个API,用于创建可用于任何给定角度组件的动态键盘快捷键。以下是用于表示Angular 角度服务回调命令组合 安装程序,angular,typescript,Angular,Typescript,我一直在开发一个API,用于创建可用于任何给定角度组件的动态键盘快捷键。以下是用于表示快捷方式的模型: export class Shortcut { keyCode: number; command: Function; args?: any; constructor(keyCode: number, command: Function, args?: any[]) { this.keyCode = keyCode; this.command = comman
快捷方式的模型:
export class Shortcut {
keyCode: number;
command: Function;
args?: any;
constructor(keyCode: number, command: Function, args?: any[]) {
this.keyCode = keyCode;
this.command = command;
if (args) {
this.args = args;
}
}
}
createMarkdown(editor: ElementRef, markdown: string) {
function getEditorValues(editor: ElementRef): EditorValues {
return new EditorValues(
editor.nativeElement.selectionStart,
editor.nativeElement.selectionEnd,
editor.nativeElement.value.length,
editor.nativeElement.value
);
}
const values = getEditorValues(editor);
if (values.start === values.end) {
editor.nativeElement.value = `${values.zeroToStart}${markdown}${values.startToLength}`;
} else {
editor.nativeElement.value = `${values.zeroToStart}${markdown}${values.startToLength}`;
}
}
预期用途如下:
// function called in component OnInit function
initializeShortcuts() {
this.shortcutService
.addShortcut(
KeyCodes.One,
this.md.createMarkdown,
[this.mdEditor, '#']
);
}
在组件模板中,根据文本区域检查keydown
事件,文本区域反过来调用ShortcutService
上的checkShortcut
函数。以下是整个服务:
import { Injectable } from '@angular/core';
import { Shortcut } from './shortcut';
@Injectable()
export class ShortcutService {
shortcuts = new Array<Shortcut>();
checkShortcut(event: KeyboardEvent) {
if (event.ctrlKey) {
const result = this.shortcuts.filter((s: Shortcut) => {
return s.keyCode === event.keyCode;
})[0];
if (result) {
console.log(result);
event.preventDefault();
result.args ? result.command(...result.args) : result.command();
}
}
}
addShortcut(keyCode: number, command: Function, args?: any[]) {
this.shortcuts.push(new Shortcut(keyCode, command, args));
}
removeShortcut(shortcut: Shortcut) {
const index = this.shortcuts.indexOf(shortcut);
this.shortcuts.splice(index, 1);
}
}
如果我在服务本身中定义了getEditorValues()
,并在分配value
常量时引用了该函数调用,则会抛出一个错误,因为对象未定义
有没有更好的方法来实现这样的功能,即可以在回调函数之外访问依赖功能
请参阅示例。您可以通过使用箭头函数将函数的上下文包装起来,从而保留该函数的上下文。而不是通过这个:
this.md.createMarkdown
通过以下程序:
(...params) => this.md.createMarkdown(...params)
this.md.createMarkdown.bind(this)
或者,您可以通过传递以下内容来绑定this
:
(...params) => this.md.createMarkdown(...params)
this.md.createMarkdown.bind(this)
也许这就是你要找的?您可以将上下文绑定到回调。老实说,我很难理解您的问题部分中解释的问题。但是,如果我理解您在传递对象的函数时,this
绑定丢失的问题,请不要将该函数传递给add快捷方式,而是将其包装在箭头函数中以保持this
上下文。感谢@httpNick,bind
最终成为解决方案的一部分。非常感谢!我遇到的问题确实与指定这个上下文有关,而这正是我所需要的。您提出的第二种方法非常有效,因为它允许我指定此
的上下文。在第一个实例中,我将被限制在调用组件的上下文中。结果是this.md.createMarkdown.bind(this.md)
。