[英]How to “react” on data changes with RxJS?
RxJS初學者:我在使用RxJS保存和跟蹤數據更改時遇到問題。 假設我在小視圖/小部件中構建我的應用程序,並且每個視圖/小部件都有自己的狀態,應該對數據更改執行操作。 我怎么做?
更具體的例子。 假設我有一個名為Widget
的小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
),只能filter
主題( widgetState
)。
使用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.