Simple question from NaCl newbie ...
In my javascript, I post a message to the NaCl module.
How do I execute a callback in the javascript after this message is handled by the NaCl module?
In the getting-started-tutorial, the following example is given.
function moduleDidLoad() {
HelloTutorialModule = document.getElementById('hello_tutorial');
updateStatus('SUCCESS');
// Send a message to the Native Client module
HelloTutorialModule.postMessage('hello');
}
How do I execute a callback function in HelloTutorialModule.postMessage('hello'); ?
Thanks.
There is no direct way to get a callback that a particular message was received by the NaCl module. You can do it yourself manually, however by passing along an id, and mapping ids to callbacks.
Something like this (untested):
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);
Then in the NaCl module:
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);
}