如何在Typescript ES6类中扩展Backbone.Events?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何在Typescript ES6类中扩展Backbone.Events?相关的知识,希望对你有一定的参考价值。

我正在尝试将Backbone的Events属性附加到TypeScript类上,但是当我这样做时......

class Foo {
    constructor () {
        _.assign(this, Backbone.Events); // or _.extend()
        this.stopListening(this.otherInstance);
    }
}

let bar = new Foo();
bar.on("myevent", handler);

...我得到这些编译时错误:

  • Error TS2339: Property 'stopListening' does not exist on type 'Foo'.
  • Error TS2339: Property 'on' does not exist on type 'Foo'.

我不太熟悉TypeScript如何处理这个问题,但它似乎可以处理它。

注意:寻找一个易于应用于多个类的解决方案,这些类也需要Backbone.Events功能(即,我不想将所有on,off,listenTo...方法或一些时髦的代理方法复制/粘贴到需要它们的每个类)。

由于Backbone.Events只是一个对象,我无法使用普通的ES6语法扩展它。例)

class Foo extends Backbone.Events {}

想法?

答案

而不是_.assign如果你使用_.extend它会工作,

这是一个Plunker

    class Foo {
      constructor () {
         _.extend(this, Backbone.Events);
      }
    }

    let bar : any = new Foo();

    bar.on("alert", function(msg) {
      alert("Triggered " + msg);
    });

    bar.trigger("alert", "an event");

更新的代码,以便它不会给出编译时错误。

UPDATE

你可以创建一个具有为Backbone.Events定义的所有函数的类,它的构造函数可以扩展Backbone.Events,它将覆盖刚为intellisense和类型检查定义的所有方法。

更新了plunker

 class CustomEvents {
    constructor() {
      _.extend(this, Backbone.Events);
    }

    on(eventName: string, callback?: Function, context?: any): any { return; };
    off(eventName?: string, callback?: Function, context?: any): any { return; };
    trigger(eventName: string, ...args: any[]): any { return; };
    bind(eventName: string, callback: Function, context?: any): any { return; };
    unbind(eventName?: string, callback?: Function, context?: any): any { return; };

    once(events: string, callback: Function, context?: any): any { return; };
    listenTo(object: any, events: string, callback: Function): any { return; };
    listenToOnce(object: any, events: string, callback: Function): any { return; };
    stopListening(object?: any, events?: string, callback?: Function): any { return; };
  }

你可以使用下面的CustomEvents类扩展任何类,

  class Foo extends CustomEvents {
    constructor(){
      super(); 
    }
  }

enter image description here

希望这可以帮助!!

另一答案

Backbone.Events上,事件处理附加在对象本身而不是它的.prototype上,以下是如何纠正:

import {Events} from 'backbone';

interface IEventEmitter extends Events {
    emit(event: string, ...args: any[]);
}

function _EventEmitter() {}
_EventEmitter.prototype = Events;
_EventEmitter.prototype.emit = (Events as any).trigger;
export const EventEmitter: new() => IEventEmitter
    = _EventEmitter as any as new() => IEventEmitter;

现在通过继承使用它:

class Dog extends EventEmitter {

}

var dog = new Dog;
dog.on('bark', () => console.log('Dog just barked'));
dog.emit('bark');
另一答案
  1. 使用这里的打字 - https://www.npmjs.com/package/@types/backbone
  2. 在包含Backbone脚本后立即编写Backbone.EventsMixin的实现: