javascript觀察者模式學(xué)習(xí)筆記
首先是觀察者模式代碼
// eventProxy.js
'use strict';
const eventProxy = {
onObj: {},
oneObj: {},
on: function(key, fn) {
if(this.onObj[key] === undefined) {
this.onObj[key] = [];
}
this.onObj[key].push(fn);
},
one: function(key, fn) {
if(this.oneObj[key] === undefined) {
this.oneObj[key] = [];
}
this.oneObj[key].push(fn);
},
off: function(key) {
this.onObj[key] = [];
this.oneObj[key] = [];
},
trigger: function() {
let key, args;
if(arguments.length == 0) {
return false;
}
key = arguments[0];
args = [].concat(Array.prototype.slice.call(arguments, 1));
if(this.onObj[key] !== undefined
&& this.onObj[key].length > 0) {
for(let i in this.onObj[key]) {
this.onObj[key][i].apply(null, args);
}
}
if(this.oneObj[key] !== undefined
&& this.oneObj[key].length > 0) {
for(let i in this.oneObj[key]) {
this.oneObj[key][i].apply(null, args);
this.oneObj[key][i] = undefined;
}
this.oneObj[key] = [];
}
}
};
export default eventProxy;
在觀察著模式的運(yùn)用當(dāng)中。react組件間的通信會(huì)變得異常簡(jiǎn)單呛伴,而且可以減少組件間的耦合。
import eventProxy from '../eventProxy'
class Parent extends Component{
render() {
return (
<div>
<Child_1/>
<Child_2/>
</div>
);
}
}
// componentDidUpdate 與 render 方法與上例一致
class Child_1 extends Component{
componentDidMount() {
setTimeout(() => {
// 發(fā)布 msg 事件
eventProxy.trigger('msg', 'end');
}, 1000);
}
}
// componentDidUpdate 方法與上例一致
class Child_2 extends Component{
state = {
msg: 'start'
};
componentDidMount() {
// 監(jiān)聽 msg 事件
eventProxy.on('msg', (msg) => {
this.setState({
msg
});
});
}
render() {
return <div>
<p>child_2 component: {this.state.msg}</p>
<Child_2_1 />
</div>
}
}