Skip to content

Service Layer

Ke Wang edited this page Oct 3, 2021 · 8 revisions

This chapter introduces the service layer, including how to register a service module, and the commonly used service modules.

这一章介绍服务层,包括如何注册一个服务模块,以及常用的服务模块。


Word is weak, just show the code. 下面将主要贴代码,不做过多的文字解释(写文档实在太累了)。

Register a new service 注册一个服务

  • Write your service module in src/core/services/YourServiceName/.
  • 请在src/core/services/服务名/路径下编写服务模块。

src/core/services/foo/Main.ts:

// Declare if in need
declare var $tw: any;
declare function require(path: string): any;

// Import ServiceManager
import * as ServiceManager from "../ServiceManager";

// Register your Service
export function init(): void {
  ServiceManager.registerService({
    name: "Foo",                                               // Service Name                     服务名称
    tag: "$:/CodeMirrorEnhanced/Foo",                          // Addon Register Tag, nullable     插件注册标签,可为null
    onLoad: function (CodeMirror: any, cme: object): void {},  // Execute once when service is on load 当服务模块第一次加载时执行
    onHook: function (editor: any, cme: object): void {        // Execute every time when a new editor instance is created 每次编辑器实例被创建时执行
      editor.on("mousedown", function (cm: any, event: any) {  //   - editor: CodeMirror editor instance  编辑器实例
        ...                                                    //   - cme: API of CodeMirror-Enhanced     CodeMirror-Enhanced的API
      });
    },
    api: {}                                                    // API of this service, nullable    服务提供的API,可为null
  });
}

src/core/Main.ts:

import { init as initFoo } from "./services/foo/Main.ts";
initFoo();

How to fetch all addons registered to this service 如何获取一个服务模块的所有插件:

let addons: ServiceManager.Addons = ServiceManager.getAddons("Foo")

Suggest fetching the addon list from ServiceManager every time when using it, because the addon list may change. Addons can be dynamically loaded/unloaded by adding/removing the service tags. 建议在每次使用的插件列表时候都直接从ServiceManager获取,因为插件列表可能会改变。通过添加/删除服务标签,可以动态地加载/卸载附加插件。

How to get API of the service 如何获得服务的API:

cme.service.Foo.xxx
Clone this wiki locally