Rxjs 观察对象更新和变化 [英] Rxjs observing object updates and changes

查看:22
本文介绍了Rxjs 观察对象更新和变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试观察给定对象的任何更改,包括它的所有元素.

I am currently trying to observe any changes to a given object including all of it's elements.

以下代码仅在更新 object[x] 时触发,但不会在单独更新 object[x] 的元素(例如 object[x][y])时触发

The following code only fires when an object[x] is updates, but not if individually updating object[x]'s elements such as object[x][y]

<script>
  var elem = document.getElementById("test1");

var log = function(x) {
    elem.innerHTML += x + "<br/><br/><br/>";
};

var a = [{a:1,b:2},
         {a:2,b:5}
       ];


var source = Rx.Observable
.ofObjectChanges(a)
.map(function(x) {
    return JSON.stringify(x);
});


var subscription = source.subscribe(
    function (x) {log(x);},
    function (err) {log(err);},
    function () {log('Completed');}
);

a[0] = a[1];
</script>

此代码正确运行并触发.

This code runs and fires correctly.

不过.如果我改为这个

a[0]['a'] = 3;

然后什么都没有发生.

编辑

一个更好的表述方式,我如何观察对象数组的变化?

A better way to phrase this, how can I observe changes from an array of objects?

推荐答案

如果您只想更改嵌套对象:

If you want only the nested object changes:

var source = rx.Observable.from(a).flatMap(function(item) {
  return rx.Observable.ofObjectChanges(item);
});

如果您还想要像 a[0] = a[1] 之类的更改:

If you also want changes like a[0] = a[1]:

var source = rx.Observable.merge(
  rx.Observable.ofArrayChanges(a),
  rx.Observable.from(a).flatMap(function(item) {
    return rx.Observable.ofObjectChanges(item);
  })
);

flatMapselectMany(它们是相同的函数)将允许您迭代一个值并执行一个返回 Observable 的函数.来自所有这些 Observable 的值被扁平化"到返回的新流上.

The flatMap or selectMany (they are the same function) will allow you to iterate over a value and execute a function that returns an Observable. The values from all these Observables are "flattened" onto a new stream that is returned.

http://reactivex.io/documentation/operators/flatmap.html

这篇关于Rxjs 观察对象更新和变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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