Dependency Injection in Emberjs
I read some articles about Emberjs Dependency Injection(DI) and try to upgrade my old project food_ntpc to use DI. The pros of DI is to reduce gobal object and make code clean, testing easily. There are few changes.
before
I create a CategoryManager
and put in FoodNtpc
App.
1 2 3 4 5 6 |
|
It’s very easy to access through FoodNtpc.CategoryManager
everywhere. BUT it makes testing hardly and more coupling.
1 2 3 |
|
after
Only the Ember.Object class can be registered. I change class CategoryManager
to CategoryManager = Ember.Object.extend
.
Then create an initializer
to register the CategoryManager
in foodntpc:categoryManager
naming. Set singleton to true because i want only one CategoryManager in system.
1 2 3 4 5 6 7 8 9 10 11 12 |
|
Next, create another initializer to inject those dependency. We can use after
or before
to adjust initializer sequence.
In application.js
line 6 means foodntpc:categoryManager
is injected to IndexRoute and use CategoryManager
reference.
In line 7 means inject into all controller.
1 2 3 4 5 6 7 8 9 |
|
In IndexRoute, we use this.CategoryManager
to access it.
1 2 3 |
|