How can I extend Backbone.Events in a Typescript ES6 Class?

Tre*_*vor 5 javascript inheritance backbone.js typescript

I'm trying to attach Backbone's Events properties onto a TypeScript class, however when I do this...

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

let bar = new Foo();
bar.on("myevent", handler);
Run Code Online (Sandbox Code Playgroud)

...I get these compile time errors:

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

I'm not very familiar with how TypeScript would approach this, but seems like something it could handle.

Note: looking for a solution that's easy to apply to multiple classes that also need Backbone.Events functionality (ie. I don't want to copy/paste all the on,off,listenTo... methods, or some funky proxy approach, to every class that needs them).

Since Backbone.Events is just an object, I can't extend it using normal ES6 syntax. Ex)

class Foo extends Backbone.Events {}
Run Code Online (Sandbox Code Playgroud)

Ideas?

Mad*_*jan 5

而不是_.assign如果您使用_.extend它会起作用,

这是一个柱塞

    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");
Run Code Online (Sandbox Code Playgroud)

更新了代码,使其不产生编译时错误。

更新

您可以创建一个具有为其定义的所有功能的类,并且该类的Backbone.Events构造函数可以扩展Backbone.Events,该类将覆盖仅为智能感知和类型检查定义的所有方法。

更新了塞子

 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; };
  }
Run Code Online (Sandbox Code Playgroud)

您可以使用CustomEvents类扩展任何类,如下所示,

  class Foo extends CustomEvents {
    constructor(){
      super(); 
    }
  }
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

希望这可以帮助!!