手写事件总线函数和 axios 函数

一、事件总线
  1. 事件总线,如下所示:
  • eventBus,包含所有功能的事件总线对象
  • eventBus.on,绑定事件监听
  • eventBus.emit,分发事件
  • eventBus.off,解绑指定事件名的事件监听,如果没有指定解绑所有
  1. 事件总线的实现,代码如下所示:
 
export const eventBus = {
  // 保存类型与回调的容器
  callbacks: {}
}

// 绑定事件
eventBus.on = function (type, callback) {
  // 判断
  if (this.callbacks[type]) {
    // 如果 callbacks 属性中存在该类型事件
    this.callbacks[type].push(callback);
  } else {
    // 如果 callbacks 属性中不存在该类型事件
    this.callbacks[type] = [callback];
  }
}

// 触发事件
eventBus.emit = function (type, data) {
  // 判断
  if (this.callbacks[type] && this.callbacks[type].length > 0) {
    // 遍历数组
    this.callbacks[type].forEach(callback => {
      // 执行回调
      callback(data);
    });
  }
}

// 事件的解绑
eventBus.off = function (eventName) {
  // 若传入了 eventName 事件类型
  if (eventName) {
    // 只是删除了 eventName 对应的事件回调
    delete this.callbacks[eventName];
  } else {
    this.callbacks = {};
  }
}

  1. 手写实现事件总线的应用,代码如下所示:
//eventBus
eventBus.on('login', data => {
    console.log( data + '用户已经登录');
});

eventBus.on('login', data => {
    console.log( data + '登录数据已经写入');
});

eventBus.on('logout', data => {
    console.log( data + '退出登录');
});
//触发触发
// setTimeout(() => {
//     eventBus.emit('login', '张三');
// }, 2000)

//解绑事件
// eventBus.off('login');
eventBus.off();

console.log(eventBus);
二、axios 函数
  1. axios 函数,发送请求。
  2. axios 函数的实现,代码如下所示:
export function axios ({method, url, params, data}) {
  // 方法转为大写
  method = method.toUpperCase();
  // 返回值
  return new Promise((resolve, reject) => {
    // 1. 创建对象
    const xhr = new XMLHttpRequest();
    // 2. 初始化
    // 处理 params 对象 a=100&b=200
    let str = '';
    for(let k in params) {
      str += `${k}=${params[key]}&`;
    }
    str = str.slice(0, -1);
    xhr.open(method, url+'?'+str);
    // 3. 发送
    if (method === 'POST' || method === 'PUT' || method === 'DELETE') {
      // Content-type mime类型设置
      xhr.setRequestHeader('Content-type','application/json');
      // 设置请求体
      xhr.send(JSON.stringify(data));
    } else {
      xhr.send();
    }
    // 设置响应结果的类型为 JSON
    xhr.responseType = 'json';
    // 4. 处理结果
    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4) {
        // 判断响应状态码 2xx
        if (xhr.status >= 200 && xhr.status < 300) {
          // 成功的状态
          resolve({
            status: xhr.status,
            message: xhr.status,
            body: xhr.response
          });
        } else {
          reject(new Error('请求失败,状态码为' + xhr.status));
        }
      }
    }
  });
}


axios.get = function (url, options) {
  // 发送 AJAX 请求 GET
  let config = Object.assign(options, {method: 'GET', url: url});
  return axios(config);
}

axios.post = function (url, options) {
  // 发送 AJAX 请求 POST
  let config = Object.assign(options, {method: 'POST', url: url});
  return axios(config);
}

axios.put = function (url, options) {
  // 发送 AJAX 请求 PUT
  let config = Object.assign(options, {method: 'PUT', url: url});
  return axios(config);
}

axios.delete = function (url, options) {
  // 发送 AJAX 请求 DELETE
  let config = Object.assign(options, {method: 'DELETE', url: url});
  return axios(config);
}

  1. 手写实现 axios 函数的应用,代码如下所示:
// 函数
axios({
  // 请求的类型
  method: 'POST',
  // 请求的 url
  url: 'https://api.apiopen.top/getJok',
  // url 参数
  params: {
    a: 100,
    b: 200
  },
  // 请求体
  data: {
    c: 300,
    d: 400
  }
}).then(response => {
  console.log(response);
}).catch(reason => {
  console.log(reason);
});


// 调用对象方法
axios.get('https://api.apiopen.top/getJoke', {
  params: {
    a: 100,
    b: 200
  }
}).then(response => {
  console.log(response);
});

axios.post('https://api.apiopen.top/getJoke', {
  params: {
    a: 100,
    b: 200
  },
  data: {
    c: 300,
    d: 400
  }
}).then(response => {
  console.log(response);
});

axios.put('https://api.apiopen.top/getJoke', {
  params: {
    a: 100,
    b: 200
  }
}).then(response => {
  console.log(response);
});

axios.delete('https://api.apiopen.top/getJoke', {
  params: {
    a: 100,
    b: 200
  }
}).then(response => {
  console.log(response);
});
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值