@豆丁 / 稿定前端开发实习生
它能将异步的数据源封装成一个
可监听对象(Observable)
供监听者(Listener)监听
并提供丰富的
操作符(Operator)
对数据流进行处理
视频网站
Observable:可观察对象,数据源
Observer:观察者,处理数据
// without RxJS
let btn = document.getElementById('btn');
btn.addEventListener('click', function(){
console.log('You clicked the btn!');
}, false);
// with RxJS
let eventObservable = Rx.Observable.fromEvent(btn, 'click');
eventObservable.subscribe(() => {
console.log('You clicked the btn!');
});
// without RxJS
setInterval(() => {
console.log('do something regularly');
}, 1000)
// with RxJS
let intervalObservable = Rx.Observable.interval(1000);
intervalObservable.subscribe(() => {
console.log('do something regularly');
})
// without RxJS
fetch('/user')
.then((res) => {
// do something when response
})
// with RxJS
let fetchObservable = Rx.Observable.fromPromise(fetch('/user'));
fetchObservable.subscribe((res) => {
// do something when response
})
// without RxJS
let socket = new WebSocket('wss://websocket.org');
socket.addEventListener('message', (event) => {
// do something when response
});
// with RxJS
let fetchObservable = Rx.Observable.webSocket('wss://websocket.org');
fetchObservable.subscribe((res) => {
// do something when response
})
Observable 创建方法
视频网站
Observable:可观察对象,数据源
Observer:观察者,处理数据
Operator:加工数据
利用 Operator 实现事件委托
<div id="delegate">
<span>span 1</span>
<span>span 2</span>
<span>span 3</span>
<span>span 4</span>
<span>span 5</span>
</div>
点击span时,输出span的内容。并且防止频繁点击,500毫秒内只能点击一次。
利用 Operator 实现事件委托
let delegate = document.getElementById('delegate');
let debonce = 500;
let lastTime = Date.now() - debonce;
delegate.addEventListener('click', (e) => {
if (Date.now() - lastTime < debonce) return;
if (e.target.tagName !== 'SPAN') return;
console.log(e.target.innerHTML);
}, false);
利用 Operator 实现事件委托
let delegateObservable = Rx.Observable
.fromEvent(document.getElementById('delegate'), 'click')
.debounce(500)
.filter(e => e.target.tagName === 'SPAN')
.map(e => e.target.innerHTML)
delegateObservable.subscribe((val) => {
console.log(val)
});
Operator 类型
复杂的UI操作