RxJS Demo
HTML
<div class="container">
<div class="alert alert-info">
<Button id="plus">+</Button>
<Button id="minus">-</Button>
Count: <span id="result">0</span>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/3.1.1/rx.all.compat.min.js"></script>
CSS
body {
font-family: sans-serif;
padding: 10px;
}
h2 {
font-weight: bold;
display: inline-block;
margin-left: 20px;
}
.header {
background: #ECECEC;
padding: 5px;
}
JavaScript
class CustomArray extends Array {
push(e) {
super.push(e)
if (this._listeners) {
this._listeners.forEach(l => l(e))
}
}
addPushListener(listener) {
this._listeners = this._listeners || []
this._listeners.push(listener)
}
removePushListener(listener) {
if (this._listeners) {
const index = this._listeners.indexOf(listener)
if (index >= 0) {
this._listeners.splice(index, 1)
}
}
}
}
const observePushes = array => Rx.Observable.fromEventPattern(
array.addPushListener.bind(array),
array.removePushListener.bind(array)
)
const arr = new CustomArray()
const pushObservable = observePushes(arr)
const subscription = pushObservable.subscribe(e => console.log(`Added ${e}`))
arr.push(1)
arr.push(2)
arr.push(3)
arr.push("a")
subscription.dispose()
arr.push("b")