WEEX H5 Render 解读(9)之sender类

上节我们分析了stream.js的源码,这节我们继续阅读sender类。sender类提供了一个在原生调用js上提供了一个桥。


拿昨天的例子来说:

      require("@weex-module/stream").fetch({url:"http://www.baidu.com"},function(data){
        console.log(data);
      });

我们知道stream.fetch()方法是有weex框架执行的,当执行完毕时,怎么调用我写的<code>console.log(data);</code>?我想这便是sender要解决的吧。

  • 原型方法
    下面我们看一下sender类通过原型提供给外界调用的方法。
Sender.prototype = {
  // perform a callback to jsframework.
  performCallback: function (callbackId, data, keepAlive) {
    var args = [callbackId]
    data && args.push(data)
    keepAlive && args.push(keepAlive)
    _send(this.instanceId, {
      method: 'callback',
      args: args
    })
  },
  fireEvent: function (ref, type, event) {
    if (event._alreadyFired) {
      // stop bubbling up in virtual dom tree.
      return
    }
    // do not prevent default, otherwise the touchstart
    // event will no longer trigger a click event
    event._alreadyFired = true
    var evt = utils.extend({}, event)
    // The event.target must be the standard event's currentTarget.
    evt.target = evt.currentTarget
    evt.value = event.target.value
    evt.timestamp = Date.now()
    _send(this.instanceId, {
      method: 'fireEvent',
      args: [ref, type, evt]
    })
  }
}

原型方法有两种分别是performCallback和fireEvent。通过看代码我们可以知道fireEvent是用于事件触发时调用js代码时使用。

  • _send方法
    我们看到上面两个原型方法都调用了_send方法。
_send(this.instanceId, {
   method: 'callback',
   args: args
 })
/****/
_send(this.instanceId, {
   method: 'fireEvent',
   args: [ref, type, evt]
 })

但是呢,_send方法定义却非常简单。

function _send(instanceId, msg) {
  callJS(instanceId, [msg])
}

这里面的callJS是global的一个方法。主要用于把msg注入到我们写的代码中并调用它

function(data){ console.log(data); }

这里先简单说一下,调用的步骤:
. 找到需要执行函数的实例
. 找到这一个方法
. 注入调用参数
. 启动调用
.调用结果的记录

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • https://nodejs.org/api/documentation.html 工具模块 Assert 测试 ...
    KeKeMars阅读 6,453评论 0 6
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,099评论 19 139
  • ¥开启¥ 【iAPP实现进入界面执行逐一显】 〖2017-08-25 15:22:14〗 《//首先开一个线程,因...
    小菜c阅读 6,663评论 0 17
  • 几天不写简文,手有点生了,今天继续。在这几天里,我读了一下weex官方文档,以便更好的阅读阅读源码。另外呢,温习了...
    cpu_driver阅读 6,358评论 2 4
  • 工厂模式类似于现实生活中的工厂可以产生大量相似的商品,去做同样的事情,实现同样的效果;这时候需要使用工厂模式。简单...
    舟渔行舟阅读 7,929评论 2 17