0

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.

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.