如何“反应"使用 RxJS 更改数据? [英] How to "react" on data changes with RxJS?

查看:45
本文介绍了如何“反应"使用 RxJS 更改数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

RxJS beginner here: I have problems with saving and tracking data changes using 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?

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

More concrete example. Let's say I have a widget called Widget and Widget has a title and button. 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:

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

但是我不能filter订阅(widgetStateChanges),只有一个主题(widgetState).

However I can't filter a subscription (widgetStateChanges), only a subject (widgetState).

推荐答案

使用 BehaviorSubject 来跟踪可观察状态:

Use a BehaviorSubject to track observable state:

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) { ... });

这篇关于如何“反应"使用 RxJS 更改数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆