Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trigger custom event in Rx JS

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.

like image 637
Tristan Avatar asked May 11 '26 01:05

Tristan


1 Answers

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:

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.

like image 76
Christoph Avatar answered May 13 '26 15:05

Christoph



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!