Last active
May 10, 2017 18:18
-
-
Save mvaldesdeleon/725720e5ae377e842d18389fd027b89a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function storify(target = {}) { | |
const observers = {}, | |
observables = {}; | |
return new Proxy(target, { | |
get: function(target, property, receiver) { | |
if (property in observables === false) { | |
observables[property] = Rx.Observable.create(observer => { | |
observers[property] = observer; | |
if (property in target) observer.next(target[property]); | |
}).publishBehavior().refCount().skip(1); | |
} | |
return observables[property]; | |
}, | |
set: function(target, property, value, receiver) { | |
target[property] = value; | |
observers[property].next(value); | |
return true; | |
}, | |
deleteProperty: function(target, property) { | |
if (delete target[property]) { | |
observers[property].complete(); | |
delete observables[property]; | |
delete observers[property]; | |
return true; | |
} else { | |
return false; | |
} | |
} | |
}); | |
} | |
const s = storify(); | |
const x = s.myvalue; | |
x.subscribe(x => console.log('xVal', x), x => console.log('xErr', x), x => console.log('xComp', x)); | |
s.myvalue = 1; | |
// xVal 1 | |
s.myvalue = 2; | |
// xVal 2 | |
s.myvalue = 3; | |
// xVal 3 | |
const y = s.myvalue; | |
y.subscribe(y => console.log('yVal', y), y => console.log('yErr', y), y => console.log('yComp', y)); | |
// yVal 3 | |
s.myvalue = 4; | |
// xVal 4 | |
// yVal 4 | |
s.myvalue = 5; | |
// xVal 4 | |
// yVal 5 | |
delete s.myvalue; | |
// xComp | |
// yComp |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment