【问题标题】:How to implement callback after sending message to NaCl (Chrome Native Client)?向 NaCl (Chrome Native Client) 发送消息后如何实现回调?
【发布时间】:2014-05-22 17:14:16
【问题描述】:

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

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

getting-started-tutorial中,给出如下例子。

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

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

谢谢。

【问题讨论】:

    标签: javascript callback google-nativeclient ppapi


    【解决方案1】:

    没有直接的方法来获取 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);
      }
    

    【讨论】:

    猜你喜欢
    • 2019-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-24
    相关资源
    最近更新 更多