admin管理员组

文章数量:1395752

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.

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.

Share Improve this question asked Jun 26, 2010 at 23:43 TristanTristan 6,9265 gold badges43 silver badges63 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

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 ponent that you would like to expose the Observable, why not use RxJS directly rather than indirectly like so:

function Component(){
    var self = {};
    var subject = new Rx.Subject();

    //raise notifications this way
    //subject.OnNext("myData"); //could be anything, a string, an object, whatever

    self.getObservableSomething = function(){
        return subject.AsObservable();
    }
    return self;
}

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.

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

本文标签: javascriptTrigger custom event in Rx JSStack Overflow