Reputation: 2111
I am new to RxJS so I apologize for the newbie question.
I have a local javascript object defined as:
model.user = {
firstName: 'John',
lastName: 'Smith'
}
I am binding each property to an input control where the user can change the values. I would like to be able to observe this object and capture the event when the value of any of the properties change.
Is this achievable with RxJS?
Thanks.
Upvotes: 5
Views: 3061
Reputation: 4345
Instead of using an object, you can store your entire state as Observable.
Here is the example code (something similar to what people do in redux):
var fnameInput = document.getElementById('fname');
var lnameInput = document.getElementById('lname');
var jsonPre = document.getElementById('json');
var onFirstName$ = Rx.Observable.fromEvent(fnameInput, 'input');
var onLastName$ = Rx.Observable.fromEvent(lnameInput, 'input');
var initialState = {
firstName: '',
lastName: '',
};
var state$ = Rx.Observable
.merge(
onFirstName$
.map(e =>
state => Object.assign(
state,
{ firstName: e.target.value }
)
),
onLastName$
.map(e =>
state => Object.assign(
state,
{ lastName: e.target.value }
)
)
)
.scan(
(state, makeNew) => makeNew(state),
initialState
)
.startWith(initialState);
state$
.subscribe(state => {
jsonPre.innerHTML = JSON.stringify(state, null, 2);
});
<input id="fname" type="text">
<input id="lname" type="text">
<pre id="json"></pre>
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/4.0.6/rx.all.js"></script>
Upvotes: 4