RxJS 初学者:我在使用 RxJS 保存和跟踪数据更改时遇到问题。假设我在小视图/小部件中构建我的应用程序,每个视图/小部件都有自己的状态,并且应该对数据更改执行操作。我怎么做?
更具体的例子。假设我有一个名为Widget
and Widget
有标题和按钮。状态应包含标题和信息if该按钮已被单击。通过阅读 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' });
我聆听这些变化,但我不知道如何聆听save他们。如果发生某些数据更改,我还想做一些特殊的事情。像这样的东西。
widgetStateChanges.filter(function(e) {
return e.wasClicked;
}).do(function(e) {
console.log('Do something because was clicked now.');
});
然而我不能filter
订阅(widgetStateChanges
),只有一个主题(widgetState
).
Use a 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) { ... });
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)