Hi! I’m trying to determine the differences, advantages/disadvantages of services, initializers and utils? When should I use one or another? Thanks!
utilsare stateless. They’re usually utility functions, but sometimes you put constants and enums in there too.
utilsbut are allowed to hold states. They are singleton objects. In early versions of Ember, you create special controllers that holds state and inject these controllers into other controllers associated to routes. This way you can achieve cross-outlet communication.
serviceswere introduced to formalize these special controllers as standard practice.
initializersallows you to operate on the
Ember.Applicationinstance before your application boots. You can configure dependency injection and defer application boot during this time. They are sometimes used to do things that’s not standard to usual Ember applications, like reopening Ember’s classes to patch them for varies reasons. In other words, you use it to do things that Ember doesn’t usually let you do. If Ember’s opinionated nature has a rulebook, these is where you break the rules. But first, you need to learn the rules.
I’ve been reading about services and factories, and I have doubts about them. What is the difference between injecting a factory and injecting a service? Could you please explain more about this? I couldn’t see a real world difference here.
From a public API standpoint, there are no factory concepts. All factory related APIs are private to Ember internals. For beginners, it is best to pretend they don’t exist.
There are only two things you can inject, controllers and services. Services are just special controllers anyway. So you’re really only injecting controllers.
register on the application is public.
And @IAmJulianAcosta all services are automatically injected as a factory.
Ember.inject.service() later allows you to inject this factory. Its identical to
App.inject() but can be done from within anything that gets initialized by the DI container.
Its identical to lookup the dependency manually with
Usually use initializers to:
- Inject a service into a factory type. For example inject a specific service into all controllers.
- Register service-like non ember stuff.
- Do work before your application loads. I for example fetch my translations with an initializer, or initialize twitter bootstrap tooltips.
Services are to hold global application state. The current user is the best example, but it could also be a backend.
Utils is easy for stateless functions of all kind.