observable
对事件进行观察
class Event {
constructor() {
this.handlers = new Map();
this.count = 0;
}
subscribe(handler) {
this.handlers.set(++this.count, handler);
return this.count;
}
unsubscribe(idx) {
this.handlers.delete(idx);
}
// 1. 谁触发这个事件
// 2. 额外的信息(事件参数)
fire(sender, args) {
this.handlers.forEach((handler) => {
handler(sender, args);
});
}
}
class FallsIllArgs {
constructor(address) {
this.address = address;
}
}
class Person {
constructor(name, address) {
this.name = name;
this.address = address;
this.fallsIll= new Event();
}
catchCold() {
this.fallsIll.fire(this, new FallsIllArgs(this.address));
}
}
let person = new Person('张三', '游泳池');
let sub = person.fallsIll.subscribe((sender, args) => {
console.log(`${sender.name}需要医生前往${args.address}`);
})
person.catchCold();
person.fallsIll.unsubscribe(sub);
person.catchCold();
对属性进行观察
class Event {
constructor() {
this.handlers = new Map();
this.count = 0;
}
subscribe(handler) {
this.handlers.set(++this.count, handler);
return this.count;
}
unsubscribe(idx) {
this.handlers.delete(idx);
}
fire(sender, args) {
this.handlers.forEach((handler) => {
handler(sender, args);
});
}
}
class PropertyChangedArgs {
constructor(name, newValue) {
this.name = name;
this.newValue = newValue;
}
}
class Person {
constructor(age) {
this._age = age;
this.propertyChanged = new Event();
}
get age() {
return this._age;
}
set age(value) {
if (!value || this._age === value) {
return;
}
this._age = value;
this.propertyChanged.fire(this, new PropertyChangedArgs('age', value));
}
}
class RegistrationChecker {
constructor(person) {
this.person = person;
this.token = person.propertyChanged.subscribe(this.handleAgeChanged);
}
handleAgeChanged = (sender, args) => {
console.log(args.name === 'arg');
if (sender === this.person && args.name === 'age') {
if (args.newValue < 18) {
console.log(`很抱歉,您现在年龄还太小了,不能够注册`);
} else {
console.log(`现在可以开始注册了!`);
sender.propertyChanged.unsubscribe(this.token);
}
}
}
}
let person = new Person('Tom');
let checker = new RegistrationChecker(person);
for (let i = 15; i < 22; i++) {
console.log(`年龄变到了${i}`);
person.age = i;
}