Skip to content

Instantly share code, notes, and snippets.

@syul
Created August 4, 2016 09:00
Show Gist options
  • Save syul/1e669b770ba18cc2e2e83d5a35082240 to your computer and use it in GitHub Desktop.
Save syul/1e669b770ba18cc2e2e83d5a35082240 to your computer and use it in GitHub Desktop.
observable collection
'use strict';
const rx = require('rx');
let Collection = function () {
this._data = [];
this._onPush = undefined;
this._observable = rx.Observable.create((observer) => {
this._onPush = function () {
observer.onNext(this._data);
}
});
Object.defineProperty(this, 'data', {
get: () => {
return this._data;
},
set: (value) => {
throw new Error('Prohibited to change readonly property');
}
});
};
Collection.prototype.push = function(value) {
this._data.push(value);
this._onPush(value);
};
Collection.prototype.subscribe = function(cb) {
this._observable.subscribe(cb);
};
let col = new Collection();
col.subscribe(ss => console.log(ss));
col.push(1);
col.push(2);
col.push(3);
col.push(4);
col.push(5);
col.push(6);
// console output:
// [ 1 ]
// [ 1, 2 ]
// [ 1, 2, 3 ]
// [ 1, 2, 3, 4 ]
// [ 1, 2, 3, 4, 5 ]
// [ 1, 2, 3, 4, 5, 6 ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment