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

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

问题描述

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

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

以下代码仅在对象[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]

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

flatMap selectMany (它们是相同的函数)将允许您迭代一个值并执行一个返回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天全站免登陆