JavaScript编写事件驱动的回调

问题描述 投票:0回答:1

我正在编写一种库,该库将传递来自服务器的各种事件,进行一些处理并将结果传递到客户端JavaScript。我见过socket.io有类似socket.on("message", callback()}的事件。我有一个地方需要从服务器获取消息,然后像myobj.on("message",callback())一样传递给前端,还有另一种情况,我需要播放音频,然后在音频结束时触发相同的on函数具有不同的事件和回调。像myobj.on("audioEnded", callback())

我具有这样的音频播放功能:

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.)
  });

我如何编写此on函数来通知事件?

javascript function object callback
1个回答
0
投票

您可以尝试使用此“订阅”功能

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:
{
    action: ":login"
    content: {state: 1, aid: 1, name: "Super Can", info: {name: "Super Can", level: "Super Level!"},…}
}

然后您的代码应如下所示:

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();
     ....
})

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.