Search code examples
javascriptinheritancebackbone.jstypescript

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


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

...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 {}

Ideas?


Solution

  • instead of _.assign if you use _.extend it will work,

    Here is a 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");
    

    updated code so that it does not gives compile time error.

    UPDATE

    you may create a class which has all the functions defined for Backbone.Events and constructor of it can extend Backbone.Events, which will override all the methods which is just defined for intellisense and type check.

    updated the 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; };
      }
    

    and you can extend any class with CustomEvents class like below,

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

    enter image description here