function observable (value, condition, callback){
this.value = value;
this.condition = condition;
this.callback = callback;
}
observable.prototype = {
get value () {
return this._value;
},
set value (value) {
this._value = value;
if (this.condition && this.callback && this.condition (value)) {
this.callback (value);
}
}
};
condition = function (value) {
console.log ('condition', value);
return value === 2;
}
callback = function (value) {
console.info ('Big Brother is watching you!');
}
var a = new observable (0, condition, callback);
console.log ('set value to 1');
a.value = 1;
console.log ('set value to 2');
a.value = 2;
console.log ('set value to 3');
a.value = 3;
javascript - observer 范例
最新推荐文章于 2024-08-11 21:51:38 发布
本文详细探讨了JavaScript中的Observer设计模式,通过一个具体的范例展示了如何使用回调函数实现观察者订阅和通知机制,深入理解其在函数式编程中的应用。
摘要由CSDN通过智能技术生成