Skip to content

Instantly share code, notes, and snippets.

@mvaldesdeleon
Last active May 10, 2017 18:18
Show Gist options
  • Save mvaldesdeleon/725720e5ae377e842d18389fd027b89a to your computer and use it in GitHub Desktop.
Save mvaldesdeleon/725720e5ae377e842d18389fd027b89a to your computer and use it in GitHub Desktop.
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