Created
August 4, 2016 09:00
-
-
Save syul/1e669b770ba18cc2e2e83d5a35082240 to your computer and use it in GitHub Desktop.
observable collection
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
'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