没有直接的方法来获取 NaCl 模块接收到特定消息的回调。您可以自己手动完成,但是通过传递一个 id 并将 id 映射到回调。
像这样的东西(未经测试):
var idCallbackHash = {};
var nextId = 0;
function postMessageWithCallback(msg, callback) {
var id = nextId++;
idCallbackHash[id] = callback;
HelloTutorialModule.postMessage({id: id, msg: msg});
}
// Listen for messages from the NaCl module.
embedElement.addEventListener('message', function(event) {
var id = event.data.id;
var msg = event.data.msg;
var callback = idCallbackHash[id];
callback(msg);
delete idCallbackHash[id];
}, true);
然后在 NaCl 模块中:
virtual void HandleMessage(const pp::Var& var) {
pp::VarDictionary dict_var(var);
pp::Var id = dict_var.Get("id");
pp::Var msg = dict_var.Get("msg");
// Do something with the message...
pp::VarDictionary response;
response.Set("id", id);
response.Set("msg", ...);
PostMessage(response);
}