Don’t get scared of the word ‘Services’ – Ember Guide to Services

Services were introduced in Ember 1.10, replacing and improving upon the common pattern of service controllers. They’re incredibly useful for connecting to third-party APIs, connecting disparate parts of your application, and storing state that should survive route changes but not be saved to the server.

Service is an ember object that sticks around for the life of the application. You can store state and access it in almost any part of the application easily, just by injecting it.

As suggested by the core team of ember(https://guides.emberjs.com/v2.1.0/applications/services/), following things can be implemented using services:

  • Logging
  • User/session authentication
  • Geolocation
  • Third-party APIs
  • Web Sockets
  • Server-sent events or notifications
  • Server-backed API calls that may not fit Ember Data

 

Suppose we have a music app and we want to implement a simple playlist feature. The playlist will have add, remove the song.

We can write a simple code for adding the playlist feature:

//services/current-playlist.js

export default Ember.Service.extend({
  songs: [],
  add(song){
    if(this.get("fullPlaylist")){
      alert('PLaylist is full. Remove a song to add another.')
    } else {
      this.get('songs').pushObject(song)
    }
  },
  remove(song) {
    this.get('songs').removeObject(song);
  },
  includes(song){
    return this.get('songs').includes(song)
  },
  fullTeam: Ember.computed.gte('songs.length', 10)
});

 

//models/song.js
//...
currentPlaylist: Ember.inject.service(),
onPlaylist: Ember.computed('currentPlaylist.songs.[]', function(){
  return this.get('currentPlaylist').includes(this);
})

 

//components/currently-playing.js
export default Ember.Component.extend({
  currentPlaylist: Ember.inject.service(),
  playlistSongs: Ember.computed.alias('currentPlaylist.songs'),
  actions: {
    add(song){
      this.get("currentPlaylist").add(song);
    },
    remove(song){
      this.get("currentPlaylist").remove(song);
    }
  } 
});

 

 

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s