在 Rx JS 中触发自定义事件
我试图理解 Reactive JS。在 JQuery 中,我可以触发自定义事件
$(document).bind('eventbus', function(e, d) { console.log(d);});
$(document).trigger('eventbus', 'test');
并传递数据(即“测试”)。目前尚不清楚如何在 RxJS 中执行此操作。我可以尝试转换 jquery 事件,
var observable = $(document).ToObservable('eventbus');
但 observable 返回事件对象而不是我的数据对象。如何使用 RxJS 用数据触发自定义事件?我是否总是需要利用其他一些事件类型?我的目标是使用 RxJS 创建一个简单的事件总线。
I'm trying to understand Reactive JS. In JQuery I can trigger custom events as
$(document).bind('eventbus', function(e, d) { console.log(d);});
$(document).trigger('eventbus', 'test');
and pass around data (i.e. 'test'). It's not clear how to do this in RxJS. I could try to convert the jquery events as
var observable = $(document).ToObservable('eventbus');
but observable returns the event object but not my data object. How do I trigger custom events with data using RxJS? Do I always need to piggyback on some other event type? My goal is to create a simple eventbus using RxJS.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尽管如此,你的问题有点老了,已经回答了,我想与你分享我的意见。
您提到您希望将自定义事件作为 Observables。对于自定义事件,当您真正想要的不是事件而是 Observable 时,根本不需要使用 jQuery。我喜欢将 Observable 视为类固醇事件。因此,在您想要公开 Observable 的组件中,为什么不直接使用 RxJS 而不是像这样间接使用 RxJS:
一旦您开始使用 Rx,您会注意到任何事件实际上都可以是 Observable。事实上,以 F# 为例,IEvent 派生自 IObservable。
此外,当您删除 jQuery 部分时,您还可以减少与不同框架的绑定。
Even so your question is a bit old and already answered I would like to share my opinion with you.
You mentioned that you want to have your custom events as Observables. For custom events, there is no need to use jQuery at all when what you really want to have is not an event but an Observable. I like to think of an Observable as an event on steroids. So in your component that you would like to expose the Observable, why not use RxJS directly rather than indirectly like so:
Once you started using Rx you will notice that any event could actually be an Observable. In fact, in F# for example, IEvent derives from IObservable.
In addition you reduce tieing to different frameworks when you remove the jQuery part.
您应该使用 Rx.Observable.FromJQueryEvent 从 jQuery 对象获取可观察对象,而不是普通的 .ToObservable。
此链接将为您提供帮助:jQuery + RxJS
you should use Rx.Observable.FromJQueryEvent to get an observable from a jQuery object, instead of the plain .ToObservable.
This link will help you: jQuery + RxJS