Services & State

How long does your data need to live?

Route: Stateless

Controller: Lifetime of the application

View: As long as it's displayed

The Old Way

Route: Stateless

Service: Lifetime of the application

Component: As long as it's displayed

The New Way

Ways To Implement Services

  • Putting data in the application route and grabbing from your route
  • Putting data in the application controller and needsing it
  • Putting data in a standalone controller and needsing it
  • Making an Ember object and injecting it
  • Making a Service object and injecting it

Ways To Implement Services

  • Putting data in the application route and grabbing from your route
  • Putting data in the application controller and needsing it
  • Putting data in a standalone controller and needsing it
  • Making an Ember object and injecting it
  • Making a Service object and injecting it

Do this one! (1.10 or later)

ember g service my-service

This creates the service object. Just a plain Ember object!

ember g initializer my-initializer

This creates the initializer, which injects the service into other objects

Where to inject?

What to inject?

What to call it?

controller:my-controller

(this is called a container lookup)

Type of object

Object name

Anatomy of an Initializer

You can also use `before` and `after` to enforce an order!

Using an Injected Service

Good Things To Put In Services

  • User state
  • Audio players
  • Loggers
  • GeoLocation
  • Data stores (like Ember Data)

Bad Things To Put In Services

  • General-purpose functions (use utils)
  • Things that shouldn't be long-lived (use components)
  • Things that only get injected in one place (just put it there)

Thanks!

Kyle Coberly

@kylecoberly

/kylecoberly

Ember Services & State

By Kyle Coberly

Ember Services & State

How-To presentation from Denver Ember

  • 791
Loading comments...

More from Kyle Coberly