jQuery plugin for Event Driven Architecture?

2020-05-12 04:58发布

Are there any Event Driven Architecture jQuery plugins?

Step 1: Subscribing

alt text
The subscribers subscribe to the event handler in the middle, and pass in a callback method, as well as the name of the event they are listening for...

i.e. The two green subscribers will be listening for p0 events. And the blue subscriber will be listening for p1 events.


Step 2: The p0 event is fired by another component to the Event Handler

alt text

  1. A p0 event is fired to the Event Handler
  2. The event handler notifies it's subscribers of the event, calling the callback methods they specified when they subscribed in Step 1: Subscribing.

Note that the blue subscriber is not notified because it was not listening for p0 events.


Step 3: The p1 event is fired a component to the Event Handler

alt text

The p1 event is fired by another component

Just as before except that now the blue subscriber receives the event through its callback and the other two green subscribers do not receive the event.

Images by leeand00, on Flickr

I can't seem to find one, but my guess is that they just call it something else in Javascript/jquery

Also is there a name for this pattern? Because it isn't just a basic publisher/subscriber, it has to be called something else I would think.

7条回答
贼婆χ
2楼-- · 2020-05-12 05:42

Could this serve as a ligthweight message passing framework?

function MyConstructor() {
    this.MessageQueues = {};

    this.PostMessage = function (Subject) {
        var Queue = this.MessageQueues[Subject];
        if (Queue) return function() {
                                        var i = Queue.length - 1;
                                        do Queue[i]();
                                        while (i--);
                                    }
        }

    this.Listen = function (Subject, Listener) {
        var Queue = this.MessageQueues[Subject] || [];
        (this.MessageQueues[Subject] = Queue).push(Listener);
    }
}

then you could do:

var myInstance = new MyConstructor();
myInstance.Listen("some message", callback());
myInstance.Listen("some other message", anotherCallback());
myInstance.Listen("some message", yesAnotherCallback());

and later:

myInstance.PostMessage("some message");

would dispatch the queues

查看更多
登录 后发表回答