0
votes

I am building a single page music web app using Ember. Each track is represented on the page as a component. There are many tracks on a given page. When a user clicks play, the component updates its UI to reflect that and the master route keeps track of which track is currently playing.

But when I switch routes to explore other parts of the app, and then return to the one where the track is playing, Ember has destroyed and rebuilt each component, setting everything back to its initial state and making the route's current_track object obsolete.

How would I best maintain state like this across route transitions?

My route hierarchy:

master-route 
    liked-tracks
    favorite-tracks
    posted-tracks

Another way to think of this is: on soundcloud, you play a track, then navigate to a different route. When you navigate back, the playing element hasn't lost its state or been rebuilt.

2

2 Answers

1
votes

The correct way to do this is a service.

You probably would have a service player and inject that into your component. Then you have a handy place to manage all your placer things and can use this inside your component.

You can just access a property on the service and even use it in a computed property like this:

player: Ember.inject.service(),
isCurrentTrack: Ember.computed('track', 'player.currentTrack', {
  get() {
    return get(this, 'track') === get(this, 'player.currentTrack');
  }
}),

This is actually the use-case for a service!

1
votes

You can have a controller property currentTrack and pass it to the component to maintain the currently playing sound track.

Ember.Controller.extend({
  currentTrack: 0,
  actions: {
    playNext() {
      this.incrementProperty('currentTrack');
    }
  }
});


{{sound-track currentTrack=currentTrack}}

I have made Fiddle on this. Have a look at this.