robkuz
robkuz

Reputation: 9934

Can I access the "class object" from within the class body in TypeScript

Can I do something similar to CoffeeScript or Ruby where I can create class-"Macros"

class A
    # events adds the class method "listenTo" to the class (not to the prototype)
    # listenTo will make all instances of A a listener to the given Event
    events @

    # this will register instances of A to listen for SomeEvents
    # the event broker (not here in this code) will specifically look
    # for a method called "onSomeEvent(event)"
    @listenTo SomeEvent

    # and then later
    onSomeEvent: (event)-> #do what ever is needed

This will create the following Javascript code

var A;
A = (function() {
   function A() {}
   events(A);
   A.listenTo(SomeEvent);
   A.prototype.onSomeEvent = function(event) {};
   return A;
})();

Upvotes: 2

Views: 283

Answers (1)

Murat Sutunc
Murat Sutunc

Reputation: 953

Looking at your example if you write this:

function events(A:any) {
    A.listenTo = function(arg:any){alert(arg);};
}

class A {
    public onSomeEvent(event:any) {
        //do stuff  
    }
    constructor {
        events(A);
        (<any>A).listenTo("SomeEvent");
    }
}

in TypeScript, it will compile into:

function events(A) {
    A.listenTo = function (arg) {
        alert(arg);
    };
}
var A = (function () {
    function A() {
        events(A);
        (A).listenTo("SomeEvent");
    }
    A.prototype.onSomeEvent = function (event) {
    };
    return A;
})();

Upvotes: 2

Related Questions