一、事件总线
- 事件总线,如下所示:
eventBus
,包含所有功能的事件总线对象eventBus.on
,绑定事件监听eventBus.emit
,分发事件eventBus.off
,解绑指定事件名的事件监听,如果没有指定解绑所有
- 事件总线的实现,代码如下所示:
export const eventBus = {
callbacks: {}
}
eventBus.on = function (type, callback) {
if (this.callbacks[type]) {
this.callbacks[type].push(callback);
} else {
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) {
if (eventName) {
delete this.callbacks[eventName];
} else {
this.callbacks = {};
}
}
- 手写实现事件总线的应用,代码如下所示:
eventBus.on('login', data => {
console.log( data + '用户已经登录');
});
eventBus.on('login', data => {
console.log( data + '登录数据已经写入');
});
eventBus.on('logout', data => {
console.log( data + '退出登录');
});
eventBus.off();
console.log(eventBus);
二、axios 函数
axios
函数,发送请求。axios
函数的实现,代码如下所示:
export function axios ({method, url, params, data}) {
method = method.toUpperCase();
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
let str = '';
for(let k in params) {
str += `${k}=${params[key]}&`;
}
str = str.slice(0, -1);
xhr.open(method, url+'?'+str);
if (method === 'POST' || method === 'PUT' || method === 'DELETE') {
xhr.setRequestHeader('Content-type','application/json');
xhr.send(JSON.stringify(data));
} else {
xhr.send();
}
xhr.responseType = 'json';
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
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) {
let config = Object.assign(options, {method: 'GET', url: url});
return axios(config);
}
axios.post = function (url, options) {
let config = Object.assign(options, {method: 'POST', url: url});
return axios(config);
}
axios.put = function (url, options) {
let config = Object.assign(options, {method: 'PUT', url: url});
return axios(config);
}
axios.delete = function (url, options) {
let config = Object.assign(options, {method: 'DELETE', url: url});
return axios(config);
}
- 手写实现
axios
函数的应用,代码如下所示:
axios({
method: 'POST',
url: 'https://api.apiopen.top/getJok',
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);
});