-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathobservable.js
44 lines (44 loc) · 947 Bytes
/
observable.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
const Observable = (function(){
function create(){
const observable = {};
bind(observable);
observable.init();
return observable;
}
function bind(observable){
observable.next = next.bind(observable);
observable.filter = filter.bind(observable);
observable.map = map.bind(observable);
observable.subscribe = subscribe.bind(observable);
observable.init = init.bind(observable);
}
function next(value){
this.subscribers.forEach(x => x(value));
}
function subscribe(func){
this.subscribers.push(func);
return this;
}
function filter(filterFunc){
const observable = create();
this.subscribe(value => {
if(filterFunc(value)){
observable.next(value);
}
});
return observable;
}
function map(mapFunc){
const observable = create();
this.subscribe(value => {
observable.next(mapFunc(value));
});
return observable;
}
function init(){
this.subscribers = [];
}
return {
create
};
})();