events module

This commit is contained in:
DIYgod 2018-03-02 11:27:44 +08:00
parent c9e7f8aa11
commit b387833730
No known key found for this signature in database
GPG Key ID: EC0B76A252D3EF67
2 changed files with 55 additions and 16 deletions

View File

@ -0,0 +1,44 @@
class Events {
constructor () {
this.events = {};
this.audioEvents = [
'abort', 'canplay', 'canplaythrough', 'durationchange', 'emptied', 'ended', 'error',
'loadeddata', 'loadedmetadata', 'loadstart', 'mozaudioavailable', 'pause', 'play',
'playing', 'progress', 'ratechange', 'seeked', 'seeking', 'stalled', 'suspend',
'timeupdate', 'volumechange', 'waiting'
];
this.playerEvents = [];
}
on (name, callback) {
if (this.type(name) && typeof callback === 'function') {
if (!this.events[name]) {
this.events[name] = [];
}
this.events[name].push(callback);
}
}
trigger (name, info) {
if (this.events[name] && this.events[name].length) {
for (let i = 0; i < this.events[name].length; i++) {
this.events[name][i](info);
}
}
}
type (name) {
if (this.playerEvents.indexOf(name) !== -1) {
return 'player';
}
else if (this.audioEvents.indexOf(name) !== -1) {
return 'audio';
}
console.error(`Unknown event name: ${name}`);
return null;
}
}
export default Events;

View File

@ -9,6 +9,7 @@ import User from './user';
import Lrc from './lrc';
import Controller from './controller';
import Timer from './timer';
import Events from './events';
const instances = [];
@ -27,17 +28,7 @@ class APlayer {
this.audios = [];
this.mode = this.options.mode;
// define APlayer events
const eventTypes = ['play', 'pause', 'canplay', 'playing', 'ended', 'error'];
this.event = {};
for (let i = 0; i < eventTypes.length; i++) {
this.event[eventTypes[i]] = [];
}
this.trigger = (type) => {
for (let i = 0; i < this.event[type].length; i++) {
this.event[type][i]();
}
};
this.events = new Events();
// multiple music
this.playIndex = 0;
@ -145,6 +136,12 @@ class APlayer {
}
});
for (let i = 0; i < this.events.audioEvents.length; i++) {
this.audio.addEventListener(this.events.audioEvents[i], () => {
this.events.trigger(this.events.audioEvents[i]);
});
}
// show audio time: the metadata has loaded or changed
this.audio.addEventListener('durationchange', () => {
if (this.audio.duration !== 1) { // compatibility: Android browsers will output 1 at first
@ -344,12 +341,10 @@ class APlayer {
}
/**
* attach event
* bind events
*/
on (name, func) {
if (typeof func === 'function') {
this.event[name].push(func);
}
on (name, callback) {
this.events.on(name, callback);
}
/**