简体   繁体   English

通过路由转换维护组件状态-EmberJS

[英]Maintaining component state through route transitions - EmberJS

I am building a single page music web app using Ember. 我正在使用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. 当用户单击播放时,组件将更新其UI以反映该UI,并且主路径会跟踪当前正在播放的曲目。

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. 但是,当我切换路线以探索应用程序的其他部分,然后返回到正在播放曲目的那个位置时,Ember销毁并重建了每个组件,将所有内容设置为初始状态,并使该路线的current_track对象过时了。

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. 另一种思考的方式是:在soundcloud上,播放曲目,然后导航到其他路线。 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. 您可以具有控制器属性currentTrack并将其传递给组件以维护当前播放的音轨。

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. 您可能会有一个服务提供player并将其注入到您的组件中。 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! 这实际上是服务用例!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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