我很快为您实施了一些东西,它扩展了@Deewendra的评论。您会看到该应用程序由两个前述部分组成。
在服务目录
export default Ember.Service.extend({
ids: [0,1,2,3,4,5,6,7,8,9,10],
songs: Ember.computed('ids',function(){
return this.get('ids').map(id => {
return { id: id, title: `Awesome Song ${id}`}
})
}),
currentlyPlaying: '',
currentIndex: 0,
currentStatus: 'stopped',
start() {
this.setSongByIndex();
this.set('currentStatus','playing');
},
stop(){
this.set('currentStatus','stopped');
},
nextSong() {
let maxIndex = this.get('ids.length') - 1;
let currentIndex = this.get('currentIndex');
let nextIndex = currentIndex + 1;
if (nextIndex > maxIndex) {
this.stop();
} else {
this.set('currentIndex',nextIndex);
this.setSongByIndex();
}
},
previousSong() {
let maxIndex = this.get('ids.length') - 1;
let currentIndex = this.get('currentIndex');
let prevIndex = currentIndex - 1;
if (prevIndex < 0) {
this.stop();
} else {
this.set('currentIndex',prevIndex);
this.setSongByIndex();
}
},
setSongByIndex() {
const songs = this.get('songs');
const currentIndex = this.get('currentIndex');
this.set('currentlyPlaying',songs[currentIndex]);
}
});
其是通过使用Ember.inject.service()方法连接到服务的音频播放器组件
// components/audio-player.js
export default Ember.Component.extend({
audioPlayer: Ember.inject.service('audio-player'),
actions: {
start() {
this.get('audioPlayer').start();
},
stop() {
this.get('audioPlayer').stop();
},
next(){
this.get('audioPlayer').nextSong();
},
previous(){
this.get('audioPlayer').previousSong();
}
}
});
// templates/components/audio-player
Song Title: {{audioPlayer.currentlyPlaying.title}} <br/>
Audio Player Status: {{audioPlayer.currentStatus}} <br/>
<button {{action 'start'}}>Start</button> |
<button {{action 'next'}}>Next</button> |
<button {{action 'previous'}}>Previous</button> |
<button {{action 'stop'}}>Stop</button> |
的音频播放器的服务。如你所见,玩家的“状态”存在于服务中,并且组件通过html/handlebars模板与其交互,并与一个与该模板名称相当的JavaScript文件相结合,这将会处理“视图”(模板)和“状态”(服务)之间的交互。
这是一个twiddle点击进去,并进行实验。
我不确定你的经验是关于“框架”之外的编程方面的,关于网络技术等方面的问题,并且提交过这个问题想过两次,但我认为它应该比它受到的伤害更大。
一个选项是你仍然可以使用提供UI的组件,并且这个组件可以使用包含所有核心功能的audioPlayer服务,并且服务默认为singleton。(https://guides.emberjs.com/ v2.5.0/applications/services /) –