我很快爲您實施了一些東西,它擴展了@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 /) –