Shri
Shri

Reputation: 751

JavaScript writing event driven callbacks

I'm writing a sort of library that will pass various events coming from the server, do some processing and pass the result into the client side JavaScript. I've seen socket.io having events like socket.on("message", callback()}. I have a place where I need to get the message from server and pass it to the frontend like myobj.on("message",callback()) and there is another scenario where I need to play an audio and then when the audio ends I need to fire the same on function with a different event and callback. Like myobj.on("audioEnded", callback()).

I'm having the audio playback function like this:

var self = this;

this.socket.on("audio", function (audio) {
    audio = JSON.parse(audio);
    var audioUrl =
      "data:audio/ogg;base64," + audio.data;
    self.audioElem = new Audio();
    self.audioElem.src = audioUrl;
    self.audioElem.play();
    self.audioElem.onended = (I want to notify the on function of the frontend JavaScript from here.)
  });

How do I write this on function for notifying events?

Upvotes: 0

Views: 54

Answers (1)

Soul Clinic
Soul Clinic

Reputation: 1299

You can try this `subscribe' function

const Subscriptions = {}
function subscribe (type, callback) {  
    const current = Subscriptions[type]
    if (current) {
        current.push(callback)
    } else {
        Subscriptions[type] = [callback]
    }
}
function send (action, value) {
    ws.send(JSON.stringify({ action, value }))  
}
ws.onmessage = evt => {     // ws -> websocket
    const info = JSON.parse(evt.data)    
    const { action, content } = info

    const handlers = Subscriptions[action]
    handlers && handlers.forEach(callback => callback(content, info))
}
// And all your socket messages should look like this:

//send(':login', { phone: '15089320000', password: 'xxxxx' })
subscribe(':login', (content, info) => ...)
{
    action: ":login"
    content: {state: 1, aid: 1, name: "Super Can", info: {name: "Super Can", level: "Super Level!"},…}
}

Then your codes should be looked like:

subscribe('audio', audio => {   // audio is already a JSON, no need to parse again
    const audioUrl =
      "data:audio/ogg;base64," + audio.data;
    self.audioElem = new Audio();
     ....
})

BUT I am not using socket.io, using WebSocket instead.

enter image description here

Upvotes: 1

Related Questions