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

时间:2016-05-19 20:23:37

标签: javascript inheritance backbone.js typescript

我正在尝试将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 {}

想法?

3 个答案:

答案 0 :(得分:4)

而不是_.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");

更新了代码,因此它不会产生编译时错误。

<强>更新

你可以创建一个具有为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

希望这会有所帮助!!

答案 1 :(得分:1)

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');

答案 2 :(得分:0)

  1. 使用此处的键入内容-https://www.npmjs.com/package/@types/backbone
  2. 在包含Backbone脚本之后的某处编写Backbone.EventsMixin的实现:

Backbone.EventsMixin = function () {
    _.assign(this, Backbone.Events);
}

  1. 然后可以像这样使用它:

class SomeClass extends Backbone.EventsMixin