weex社区JavaScript学习笔记首页投稿(暂停使用,暂停投稿)

WEEX H5 Render 解读(8)之stream类续

2016-08-03  本文已影响373人  cpu_driver

上节我们阅读了stream类中的两种方法sendhttp和fetch,这节我们继续阅读stream的方法。


我们应该注意到<code>_jsonp.apply(this, _callArgs)</code>和<code>_xhr.apply(this, _callArgs)</code>这两个方法。个人建议使用xhr结合cors方法进行跨域,因此这节主要在于分析_xhr的源码。
按照惯例,贴出_xhr的源码

function _xhr (config, callback, progressCallback) {
  const xhr = new XMLHttpRequest()
  xhr.responseType = config.type
  xhr.open(config.method, config.url, true)

  const headers = config.headers || {}
  for (const k in headers) {
    xhr.setRequestHeader(k, headers[k])
  }

  xhr.onload = function (res) {
    callback({
      status: xhr.status,
      ok: xhr.status >= 200 && xhr.status < 300,
      statusText: xhr.statusText,
      data: xhr.response,
      headers: xhr.getAllResponseHeaders().split('\n')
        .reduce(function (obj, headerStr) {
          const headerArr = headerStr.match(/(.+): (.+)/)
          if (headerArr) {
            obj[headerArr[1]] = headerArr[2]
          }
          return obj
        }, {})
    })
  }

  if (progressCallback) {
    xhr.onprogress = function (e) {
      progressCallback({
        readyState: xhr.readyState,
        status: xhr.status,
        length: e.loaded,
        total: e.total,
        statusText: xhr.statusText,
        headers: xhr.getAllResponseHeaders().split('\n')
          .reduce(function (obj, headerStr) {
            const headerArr = headerStr.match(/(.+): (.+)/)
            if (headerArr) {
              obj[headerArr[1]] = headerArr[2]
            }
            return obj
          }, {})
      })
    }
  }

  xhr.onerror = function (err) {
    logger.error('unexpected error in _xhr for \'fetch\' API', err)
    callback({
      status: ERROR_STATE,
      ok: false,
      statusText: '',
      data: '',
      headers: {}
    })
  }

  xhr.send(config.body)
}

<code>function _xhr (config, callback, progressCallback) {}</code>和<code>_xhr.apply(this, _callArgs)</code>相对应。XX.apply(,)中,XX是一个函数,apply的第一个参数是指代作用域,第二个参数是XX函数的参数列表。(如果对这种方式不了解可以,查阅js相关文档)

const xhr = new XMLHttpRequest()
xhr.setRequestHeader(k, headers[k])
xhr.onload = function (res) {}
xhr.onprogress = function (e) {}
hr.onerror = function (err) {}
xhr.send(config.body)

这是典型的XmlHttpRequest对象的使用,XmlHttpRequest是前端开发中使用最频繁的一个方法,可以参考百度百科
其中下面的一段代码

headers: xhr.getAllResponseHeaders().split('\n')
          .reduce(function (obj, headerStr) {
            const headerArr = headerStr.match(/(.+): (.+)/)
            if (headerArr) {
              obj[headerArr[1]] = headerArr[2]
            }
            return obj
          }, {})

是用来把字符串的headers变为js对象的的请求头。数组的reduce方法可以实现相近的两个元素调用同一个方法,同时返回新的对象的方法。obj是数组的前一个元素,headerStr是后一个元素。
代码 <code>obj[headerArr[1]] = headerArr[2]</code>之所以从1开始是因为0元素为原字符串(js 正则表达的匹配规则)。


stream到此已经分析完毕,下节我们分析sender.js。sender.js的路径为:


。再次感谢阅读,如有错误欢迎提意见啊

上一篇 下一篇

猜你喜欢

热点阅读