Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJS observe an object

Tags:

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.

like image 850
dpdragnev Avatar asked Dec 21 '16 17:12

dpdragnev


1 Answers

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>
like image 147
Oles Savluk Avatar answered Sep 26 '22 16:09

Oles Savluk