Reactivity
「當值改變時,做些什麼」
code:javascript
const pubSub = {
events: {},
subscribe(event, callback) {
this.eventsevent.push(callback); },
publish(event, data) {
if (this.eventsevent) this.eventsevent.forEach(callback => callback(data)); }
};
pubSub.subscribe('update', data => console.log(data));
pubSub.publish('update', 'Hello world!');
Observer
觀察者模式
code:javascript
class Subject {
constructor() {
this.observers = [];
}
addObserver(observer) {
this.observers.push(observer);
}
removeObserver(observer) {
const index = this.observers.indexOf(observer);
if (index > -1) {
this.observers.splice(index, 1);
}
}
notify(data) {
this.observers.forEach(observer => observer.update(data));
}
}
class Observer {
update(data) {
console.log(data);
}
}
const subject = new Subject();
const observer = new Observer();
subject.addObserver(observer);
subject.notify('Hello world!');
Object.defineProperty
生態系
Web Animations API