read

This feature is only available from Ember 1.10.0+.

Some examples when services could be used are:

  • Interfacing with a geolocation API
  • Coordinating drag-and-drop events (between components for example)
  • Consuming push events from a server
  • Using a non-CRUD server API

To create a player service type ember generate service player or create a file manually:

1
2
3
app/
services/
player.js

Services are automatically detected and registered by placing them in the services directory.

To implement a service, just export a subclass of Ember.Service

1
2
3
4
5
6
7
8
import Ember from 'ember';
export default Ember.Service.extend({
currentTime: 1,
isPlaying: false,
play: function() {
console.log('Playing...');
}
});

To use it in components (or routes, controllers etc.) or any other Ember Object:

1
2
3
4
5
6
7
8
import Ember from 'ember';
export default Ember.Component.extend({
player: Ember.inject.service(),
actions: {
play: function() {
this.get('player').play();
},
});

The name passed into the service function is not required if property name matches the service name, so it is often omitted and not written like this:

1
player: Ember.inject.service('player')

Services can then be used in the templates like so (replace < > with double curly braces (handlebars syntax):

1
<audio-control isPlaying=player.isPlaying>

or with helpers:

1
<format-duration player.currentTime>

Services are only instantiated once. This means that there is instance of the service that is never destroyed as long as your application is running.

Image

Algoholic's Blog

It's not what you know, it's what you do with what little you know...

Back to Overview