0

来自 NaCl 新手的简单问题...

在我的 javascript 中,我向 NaCl 模块发布了一条消息。
在 NaCl 模块处理此消息后,如何在 javascript 中执行回调?

入门教程中,给出了以下示例。

 function moduleDidLoad() {
      HelloTutorialModule = document.getElementById('hello_tutorial');
      updateStatus('SUCCESS');
      // Send a message to the Native Client module
      HelloTutorialModule.postMessage('hello');
    }

如何在 HelloTutorialModule.postMessage('hello') 中执行回调函数;?

谢谢。

4

1 回答 1

7

没有直接的方法来获取 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);
  }
于 2014-05-22T21:13:47.607 回答