如何用RxJS对数据变化做出“反应”?

时间:2015-01-27 07:00:52

标签: javascript rxjs

RxJS初学者:我在使用RxJS保存和跟踪数据更改时遇到问题。假设我在小视图/小部件中构建我的应用程序,并且每个视图/小部件都有自己的状态,应该对数据更改执行操作。我该怎么做?

更具体的例子。假设我有一个名为Widget的小部件,Widget有一个标题和按钮。如果按钮已被点击,则状态应包含标题和信息。从阅读RxJS的文档看,这似乎是一个很好的起点:

var widgetState = new Rx.Subject().startWith({
  wasClicked: false,
  title: 'foo'
});

现在我希望在某些数据发生变化时收到通知:

var widgetStateChanges = widgetState.subscribe(function(data) {
  console.log('data: ', data);
  // what do i do with the data here?
  // i would like to merge the new data into the old state
});

widgetStateChanges.onNext({ title: 'bar' });

我听取了这些更改,但我不知道如何保存它们。如果发生某些数据变化,我还想做一些特别的事情。这样的事情。

widgetStateChanges.filter(function(e) {
  return e.wasClicked;
}).do(function(e) {
  console.log('Do something because was clicked now.');
});

但我不能filter订阅(widgetStateChanges),只能是主题(widgetState)。

1 个答案:

答案 0 :(得分:8)

使用BehaviorSubject跟踪可观察状态:

var widgetState = new Rx.BehaviorSubject({ wasClicked: false, title: 'foo' });

// change state, probably in response to UI events
// Note we always set the full state, not just the "delta"
widgetState.onNext({ wasClicked: true, title: 'foo2' });

// example listening to title input field and updating state
// assumes rxjs-jquery
$("#title").onAsObservable("change").subscribe (function (ev) {
    var oldState = widgetState.value;
    var newTitle = $("#title").val();
    // do not mutate the oldState object, instead clone it and change the title
    var newState = $.extend({}, oldState, { title: newTitle });

    // send the update
    widgetState.onNext(newState);
});

// listen to new state values, probably to update your HTML?
widgetState.subscribe(function (newState) { ... });

// listen only when wasClicked is true
widgetState
    .filter(function (s) { return s.wasClicked; })
    .subscribe(function (s) { ... });