partyelite
partyelite

Reputation: 892

Import object in class using TypeScript

I am new to Javascript and TypeScript and I am wondering if it is possible to do some kind of dependency injection (maybe using require.js)

I have two classes in same module

module MyWebApp {
    export class ViewRouter {
           ... some class methods
    }
}

module MyWebApp {
    export class MyViewModel{
        private router: ViewRouter;

        constructor(router:ViewRouter router) {
           this.router = router;
        }
    }
}

Every time I need MyViewModel I have to instantiate ViewRouter var vm = new MyViewModel(new ViewRouter());

Is there any way around this? I thought that Require.js could help me solve my problem but I don't know how to use it with TypeScript.

Thank you.

Upvotes: 0

Views: 1318

Answers (1)

basarat
basarat

Reputation: 275957

If you want a new instance every time you should probably do:

class MyViewModel{
    private router: ViewRouter;

    constructor() {
       this.router = new ViewRouter();
    }
}

Now if you want a "single" shared instance you can do:

module MyWebApp {
    export class ViewRouter {
           ... some class methods
    }

    export var router = new ViewRouter();       
}

and use router

Using RequireJS can do the same thing for your, but the principal idea will not change there. RequireJS is not an IOC container.

There are bunch of javascript IOC containers out there and I don't have a recommendation on that : Google search

Upvotes: 1

Related Questions