使用 Proxy 结合观察者模式,模拟一个实现一个简单的双向绑定
<input type="text" id="input" />
<div id="container"></div>
var input = document.getElementById("input");
var container = document.getElementById("container");
var data = {
value: "",
};
class EventEmitter {
constructor() {
this.listenersMap = {};
}
on(eventName, listener) {
this.listenersMap.hasOwnProperty(eventName)
? this.listenersMap[eventName].push(listener)
: (this.listenersMap[eventName] = [listener]);
return this;
}
once(eventName, listener) {
listener._once = true;
this.listenersMap.hasOwnProperty(eventName)
? this.listenersMap[eventName].push(listener)
: (this.listenersMap[eventName] = [listener]);
return this;
}
emit(eventName) {
const args = [].slice.call(arguments, 1);
this.listenersMap[eventName] &&
(this.listenersMap[eventName] = this.listenersMap[eventName].filter(
(listener, index) => {
listener.apply(null, args);
return !listener._once;
}
));
return this;
}
off(eventName, fn) {
this.listenersMap[eventName] &&
(this.listenersMap[eventName] = this.listenersMap[eventName].filter(
(listener, index) => {
return listener !== fn;
}
));
}
listeners(eventName) {
return this.listenersMap[eventName];
}
}
var event = new EventEmitter();
event.on("change", function (value) {
container.innerHTML = value;
});
var newData = new Proxy(data, {
set(target, prop, value) {
event.emit("change", value);
return Reflect.set(...arguments);
},
get(target, prop, value) {
return Reflect.get(...arguments);
},
});
input.oninput = function () {
newData.value = input.value;
};