在Angular2应用程序中使用element-resize-detector库

时间:2016-12-07 21:31:34

标签: javascript angular typescript2.0

我正在尝试在Angular2应用程序中使用元素调整大小检测器库(https://github.com/wnr/element-resize-detector)。

根据我有限的JS模块知识,该库似乎采用CommonJS格式。经过多次尝试,我创建了以下定义文件(* .d.ts):

declare module ResizeDetector {
  function ResizeDetector(options: any): ResizeDetector.Erd;

  interface Erd {
    listenTo(element: any, resizeCallback: any): void;
    uninstall(element: any): void;
  }
}
export = ResizeDetector;

然后我在我的TypeScript代码中使用以下import语句:

import * as ResizeDetector from 'element-resize-detector';

运行我的应用程序并使用console.log('ResizeDetector', ResizeDetector)时,会记录以下输出:

ResizeDetector function (options) {
    options = options || {};

    //idHandler is currently not an option to the listenTo function, so it should not be added to globalOptions.
    var idHandler;

    if (options.…

这表明我已经成功加载了库,并且它按预期返回了一个函数。

我的问题是我现在如何开始在TypeScript中使用库?当我尝试这样的事情时:

private static resizeDetector = ResizeDetector({ strategy: 'scroll' });

我收到以下转换错误:

error TS2349: Cannot invoke an expression whose type lacks a call signature.

2 个答案:

答案 0 :(得分:5)

根据@ stone-shi的回答,这是我开始工作的方式:

定义文件:

declare module 'element-resize-detector' {
  function elementResizeDetectorMaker(options?: elementResizeDetectorMaker.ErdmOptions): elementResizeDetectorMaker.Erd;

  namespace elementResizeDetectorMaker {
    interface ErdmOptions {
      strategy?: 'scroll' | 'object';
    }

    interface Erd {
      listenTo(element: HTMLElement, callback: (elem: HTMLElement) => void): void;
      removeListener(element: HTMLElement, callback: (elem: HTMLElement) => void): void;
      removeAllListeners(element: HTMLElement): void;
      uninstall(element: HTMLElement): void;
    }
  }

  export = elementResizeDetectorMaker;
}

Ts档

import * as elementResizeDetectorMaker from 'element-resize-detector';

    let _elementResizeDetector = elementResizeDetectorMaker({
      strategy: 'scroll'
    });

答案 1 :(得分:3)

元素调整大小-detector.d.ts

declare function elementResizeDetectorMaker(options?: elementResizeDetectorMaker.ErdmOptions): elementResizeDetectorMaker.Erd;

declare namespace elementResizeDetectorMaker {
    interface ErdmOptions {
        strategy?: 'scroll' | 'object';
    }

    interface Erd {
        listenTo(element: HTMLElement, callback: (elem: HTMLElement) => void);
        removeListener(element: HTMLElement, callback: (elem: HTMLElement) => void);
        removeAllListeners(element: HTMLElement);
        uninstall(element: HTMLElement);
    }
}

export = elementResizeDetectorMaker;

消费

let resizeDetector = elementResizeDetectorMaker({ strategy: 'scroll'});
resizeDetector.listenTo(document.getElementById('abc'), (elem: HTMLElement) => {
    console.log(elem.offsetWidth, elem.offsetHeight);
})