浏览器

2021-05-02  本文已影响0人  世玮

什么是浏览器对象模型

BOM :Browser Object Model(浏览器对象模型),浏览器模型提供了独立于内容的、可以与浏览器窗口进行滑动的对象结构,就是浏览器提供的 API
其主要对象有:

  1. window 对象——BOM 的核心,是 js 访问浏览器的接口,也是 ES 规定的 Global 对象
  2. location 对象:提供当前窗口中的加载的文档有关的信息和一些导航功能。既是 window 对象属 性,也是 document 的对象属性
  3. navigation 对象:获取浏览器的系统信息
  4. screen 对象:用来表示浏览器窗口外部的显示器的信息等
  5. history 对象:保存用户上网的历史信息

浏览器事件模型中的过程主要分为三个阶段:捕获阶段、目标阶段、冒泡阶段。

事件模型.jpg

添加事件

所以我们常常写一个事件监听的时候,往往会这样兼容 :

function hideWxMenu() {
    if (typeof WeixinJSBridge == "undefined") {
        if (document.addEventListener) {
            document.addEventListener('WeixinJSBridgeReady', hideWXOptionMenu, false);
        } else if (document.attachEvent) {
            document.attachEvent('WeixinJSBridgeReady', hideWXOptionMenu);
            document.attachEvent('onWeixinJSBridgeReady', hideWXOptionMenu);
        }
    } else {
        WeixinJSBridge.call('hideOptionMenu');
    }
}

阻止事件

import React, { Component } from "react";
import './App.css';

class App extends Component {

  constructor(props){
    super(props);
  }
  childClick = (e) => {
    //console.log(e.target); //当前点击的元素
    //console.log(e.currentTarget); //绑定监听事件的元素
    console.log("child click");
  };

  childClickNew = (e)=>{
    console.log("child clickNew");
  }

  parentClick = () => {
    console.log("parent click");
  };

  componentDidMount() {
    let parent = document.getElementById("parent");
    let child = document.getElementById("child");
    parent.addEventListener("click", this.parentClick, false);
    child.addEventListener("click", this.childClick, false);
    child.addEventListener("click", this.childClickNew, false);
  }

  componentWillUnmount(){
    //todo:  移除事件的监听 ,防止内存泄漏
  }

  render() {
    return (
      <div id="parent">
        <button id="child">click child!</button>
      </div>
    );
  }
}

export default App;

//控制台输出的结果为: 
//child click
//child clickNew
//parent click

//如果在childClick 中加入e.stopPropagation();
//控制台输出的结果为: 
//child click
//child clickNew

//如果把addEventListener的第三个参数改成true;
//控制台输出的结果为:
//parent click 
//child click
//child clickNew

//如果在parentClick 中加入e.stopPropagation();
//控制台输出的结果为:
//parent click 
  childClick = (e) => {
    console.log("child click");
    e.stopImmediatePropagation();
  };

//控制台输出的结果为: 
//child click
//在刚才的文件中加入一个a标签:
<a href="https://www.baidu.com" onClick={this.linkClick}>点击跳转</a>

  linkClick = (e)=>{
     console.log("link click");
  }
//点击后发现 ,控制台会打印下 link click;  并且跳转到百度链接;
//如果在linkClick中添加e.preventDefault();
//只有控制台有输出:
//link click

ajax

    (function(callback){
      let xhr = new XMLHttpRequest();
      xhr.open('GET', 'https://pagead2.googlesyndication.com/getconfig/sodar?sv=200&tid=gda&tv=r20210428&st=env');
      
      // request state change event
      xhr.onreadystatechange = function () {
          // request completed?
          if (xhr.readyState !== 4) return;
      
          if (xhr.status === 200) {
              // request successful - show response
              console.log(xhr.responseText);
              callback.call(this, xhr.responseText)
          } else {
              // request error
              console.log('HTTP error', xhr.status, xhr.statusText);
          }
      };
      // start request
      xhr.send();
  })(function(data){
      console.log(data)
  })

fetch

  • isomorphic-fetch
  require('es6-promise').polyfill();
  require('isomorphic-fetch');

  fetch('//offline-news-api.herokuapp.com/stories')
   .then(function(response) {
       if (response.status >= 400) {
           throw new Error("Bad response from server");
       }
       return response.json();
   })
   .then(function(stories) {
       console.log(stories);
   });
  • SuperAgent
   import request from 'superagent'
    request
      .post('/api/pet')
      .send({ name: 'Manny', species: 'cat' }) // sends a JSON post body
      .set('X-API-Key', 'foobar')
      .set('Accept', 'application/json')
      .end(function(err, res){
       // Calling the end function will send the request
     });

fetch注意事项

// credentials: ‘include’,( 允许 cookie 共享,跨域问题,传Cookie是必须配置)
    const defaultOptions = {
        credentials: 'include',
    };
const controller = new AbortController();
const signal = controller.signal;
setTimeout(() => controller.abort(), 5000);

fetch('/api/mobile', {
  signal, // 在option中加入signal
  method: 'POST',
  // credentials:'include',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    name: 'civen',
  })
}).then((res) => {
  return res.json()
}).then((result) => {
  console.log(result)
}).catch((err) => {
  console.log(err)
})

axios

Promise based HTTP client for the browser and node.js

特性

import axios from 'axios';

const AUTH_TOKEN = "12345";

const instance = axios.create({
    // baseURL: 'http://localhost:3010',
    timeout: 5000,
});

instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
instance.defaults.withCredentials =true; 

// 添加请求拦截器
instance.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    console.log("request==>", config);
    return config;
}, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
});

// 添加响应拦截器
instance.interceptors.response.use(function (response) {
    // 对响应数据做点什么
    console.log("response==>", response);
    return response;
}, function (error) {
    // 对响应错误做点什么
    return Promise.reject(error);
});

/**获取每日油价 */
export const getDailyOilPrice = (cityName)=>{
    return instance.get(`/h5/api/v1/oil/dailyOilPrice?city=${cityName}`)
}

//Accept: application/json, text/plain, */*
//Accept-Encoding: gzip, deflate, br
//Accept-Language: zh-CN,zh;q=0.9
//Authorization: 12345
//Connection: keep-alive

EventEmitter

//1、定义EventEmitter 构造函数:
function EventEmitter() {
    this.listeners = {};
}
//接受一个字符串 event 和一个回调函数
EventEmitter.prototype.on = function(event, callback){
       var listeners = this.listeners;
    //listeners[event] 存储事件的 回调
    if (listeners[event] instanceof Array) {
        if (listeners[event].indexOf(callback) === -1) {
            listeners[event].push(callback);
        }
    } else {
        listeners[event] = [].concat(callback);
    }
}
EventEmitter.prototype.addListener = EventEmitter.prototype.on;

//按监听器的顺序执行执行每个监听器
EventEmitter.prototype.emit = function (event) {
   // 伪数组 转换成真数组
    var args = Array.prototype.slice.call(arguments);
    args.shift();  //第一个参数为event, 剔除掉 
    this.listeners[event].forEach(cb => {
        cb.apply(null, args);
    });
}

// todo: ......
上一篇下一篇

猜你喜欢

热点阅读