为 clipboard.js 库写类型文件

​ 开源库github地址:https://github.com/zenorocha/clipboard.js

​ 因未深入学习和使用clipboard.js库,只是粗略看了下源码和简要看了下文档了解其基本用法,写了如下类型声明文库。不足或不对之处还请见谅。

​ 为避免在编写时编辑器智能感知提示为clipboard.js中申明的定义文件,所以特意将名字修改为MyClipboard进行测试;

type Trigger = String | HTMLElement | HTMLCollection | NodeList;
// on添加监听回调方法
interface IOnCallbackFunParams {
  action: string;
  text: string;
  trigger: HTMLElement;
  clearSelection: () => void;
}
//  第二个参数
//  参照https://github.com/zenorocha/clipboard.js#advanced-options定义
interface IOptions {
  target?: (trigger: Trigger) => Node;
  text?: (trigger: Trigger) => string;
  container?: HTMLElement;
}

type Action = ["copy", "cut"];
type MyEventType = "success" | "error";
type AttributeValue = string | null | undefined;
type OnCallbackFun = (e: IOnCallbackFunParams) => void;

// 参照源码定义包含方法,因为继承于Emitter,未深入研究Emitter的实现,所以只简要申明了on方法的定义
declare class MyClipboard {
  constructor(trigger: Trigger, options?: IOptions);
  resolveOptions(any: {}): void;
  listenClick(trigger: Trigger): void;
  onClick(e: Event): void;
  defaultAction(trigger: Trigger): AttributeValue;
  defaultTarget(trigger: Trigger): Element | null | undefined;
  static isSupported(action?: Action): boolean;
  defaultText(trigger: Trigger): AttributeValue;
  destroy(): void;

  // 继承自Emitter的方法
  on(eventName: MyEventType, callback: OnCallbackFun): void;
}

// 测试使用
const clipboard = new MyClipboard('.btn', {
  text: (e: any) => {
    return '123';
  },
  container: document.createElement('div')
});
clipboard.on("success", (e) => {
  console.log(e.action);
  console.log(e.text);
  console.log(e.trigger);
  e.clearSelection()
});
clipboard.on("error", (e) => {
  console.log(e.action);
  console.log(e.text);
  console.log(e.trigger);
  e.clearSelection()
});
clipboard.destroy();
Copyright © imooc-lego (2020 - present) all right reserved,powered by GitbookFile Modify: 2021-06-27 08:04:56

results matching ""

    No results matching ""