简体   繁体   English

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

[英]How to “react” on data changes with RxJS?

RxJS beginner here: I have problems with saving and tracking data changes using RxJS. RxJS初学者:我在使用RxJS保存和跟踪数据更改时遇到问题。 Say I structure my app in small views/widgets and every view/widget has its own state and should do things on data changes. 假设我在小视图/小部件中构建我的应用程序,并且每个视图/小部件都有自己的状态,应该对数据更改执行操作。 How do I do that? 我怎么做?

More concrete example. 更具体的例子。 Let's say I have a widget called Widget and Widget has a title and button. 假设我有一个名为Widget的小WidgetWidget有一个标题和按钮。 The state should contain the title and the information if the button was already clicked. 如果已单击按钮,则状态应包含标题和信息。 From reading the docs of RxJS it seems this would be a good starting point: 从阅读RxJS的文档看,这似乎是一个很好的起点:

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

Now I want to be notified if some data changes: 现在我希望在某些数据发生变化时收到通知:

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' });

I listen to the changes, but I don't know how to save them. 我听到了变化,但我不知道如何保存它们。 I would also like to do special things, if a certain data change happens. 如果发生某些数据变化,我还想做一些特别的事情。 Something like this. 像这样的东西。

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

However I can't filter a subscription ( widgetStateChanges ), only a subject ( widgetState ). 但是我无法filter订阅( widgetStateChanges ),只能filter主题( widgetState )。

Use a BehaviorSubject to track observable state: 使用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) { ... });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM