简体   繁体   中英

Maintaining component state through route transitions - EmberJS

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.

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.

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM