Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions Observable.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,19 @@ class ObserverList {
}
add(observer) {
// todo add observer to list
this.observerList.push(observer)
}
remove(observer) {
// todo remove observer from list
const matchIndex = this.observerList.findIndex(observer => observer === observer)

if (matchIndex > -1) {
this.observerList.splice(matchIndex, 1)
}
}
count() {
// return observer list size
return this.observerList.length
}
}

Expand All @@ -26,12 +33,17 @@ class Subject {
}
addObserver(observer) {
// todo add observer
this.observers.add(observer)
}
removeObserver(observer) {
// todo remove observer
this.observers.remove(observer)
}
notify(...args) {
// todo notify
this.observers.observerList.forEach(observer => {
observer.update(...args)
});
}
}

Expand Down
32 changes: 29 additions & 3 deletions PubSub.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,41 @@ module.exports = class PubSub {
}

subscribe(type, fn) {
// todo subscribe
if (!type || !fn) return;
if (!this.subscribers[type]) {
this.subscribers[type] = []
}

this.subscribers[type].push(fn)
}

unsubscribe(type, fn) {
// todo unsubscribe
if(!type) return
const subscribeFns = this.subscribers[type]

if (!subscribeFns || subscribeFns.length === 0) return

if(!fn) this.subscribers[type] = []

for (let i = 0, len = subscribeFns.length; i < len; i++) {
if (subscribeFns[i] === fn) {
subscribeFns.splice(i, 1)
return
}
}

}

publish(type, ...args) {
// todo publish
if (!type) return
const subscribeFns = this.subscribers[type]
if (!subscribeFns || subscribeFns.length === 0) return

if (subscribeFns.length === 1) return subscribeFns[0](...args)

for (let i = 0, len = subscribeFns.length; i < len; i++) {
subscribeFns[i](...args)
}
}

}