简体   繁体   English

订阅数组更改

[英]Subscribe to array changes

I'm trying to use RxJS in an existing project that uses jQuery.我正在尝试在使用 jQuery 的现有项目中使用 RxJS。 Every time the button is clicked a new value is pushed to users .每次单击按钮时,都会向users推送一个新值。 How do I see changes to users in of(users).subscribe(...) ?如何查看更改usersof(users).subscribe(...)

<button class="hello">Hello</button>

<script src="https://unpkg.com/rxjs/bundles/rxjs.umd.min.js"></script>

const { of } = rxjs

let users = [
  { a: "b" }
]

of(users).subscribe(data => {
  console.log(data)
})

jQuery(document).on('click', '.hello', function () {
  users.push({ c: 'd' })
})

Using the RxJS scan operator, you can transform a stream into a different form, similar to how JavaScript's native .reduce() method works.使用 RxJS scan运算符,您可以将流转换为不同的形式,类似于 JavaScript 的原生.reduce()方法的工作方式。 In this example, whenever you wanted to "push" to the users array, you could simply emit another user on the newUser subject.在这个例子中,每当你想“推送”到用户数组时,你可以简单地在 newUser 主题上发出另一个用户。

// Create a new subject
const newUser = new Subject();

// Use scan to add new users into array of users
const users = newUser.pipe(scan((acc, user) => [ ...acc, user ], []));

// Subscribe to the list of users and log
users.subscribe(data => console.log(data));

// Add new user to array on document click
jQuery(document).on('click', '.hello', () => users.next({ c: 'd' }));

Alternative you can make use of the new ES6 proxy class together with Subject https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/handler/set或者,您可以将新的 ES6 代理类与 Subject https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/handler/set一起使用

let usersUpdate=new Subject()
let users = [
  { a: "b" }
]

usersUpdate.subscribe(data => {
  console.log(data)
})

let users=new Proxy([{ a: "b" }],{
set:(obj, prop, newval)=>{
    obj[prop] = newval
    userUpdate.next({obj, prop, newval})
    return true
   }
})

users.push('item')

One way would be to use BehaviorSubject一种方法是使用BehaviorSubject

So for your case would be to write following:因此,对于您的情况,请编写以下内容:

const users$ = new BehaviorSubject([{ a: 'b' }]);

users$.subscribe((users) => {
  console.log(users);
});

jQuery(document).on('click', '.hello', function() {
  const users = [...users$.value]; // write like this so that array stays immutable
  users.push({ a: 'd' });
  users$.next(users);
});

Using BehaviorSubject gives you possibility to obtain current value: users$.value .使用BehaviorSubject让您获得当前值: users$.value

After users$.next(users) event will be emitted and console.log(users) will happen inside subscribeusers$.next(users)事件将被发出后, console.log(users)将在 subscribe 内发生

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM