开发者

Javascript custom events with wildcards (*)

I am making a pub/sub object for custom events and I can't figure how to add support for events like user.logged.* where it would subscribe the subscriber to the events user.logged.in and user.logged.out

Are there any resources cause Google can't help.

EDIT

Maybe in my s开发者_StackOverflow中文版ubscribe function i should check the passed event type for wildcards and subscribe to both events?


I would constraint it to just the last part be a wildcard. Then, trigger would look like

function trigger(name, data) {
    var parts = name.split('.');
    for(var i = 0; i < parts.length; i++) {
        call_subscribers(parts.slice(0, i).join('.'), data, parts.slice(i+1));
    }
}

function call_subscribers(event_name, data, remaining_event_parts) {
    for(var subscriberIndex in subscribers[event_name]) {
        subscribers[subscriberIndex](data, remaining_event_parts);
    }
}

On this examble, you would do

subscribers = [];
subscribers['user.logged'] = [
    function(data) { // here, we dont care about the remaining parts
        // do what you have to do
    }
];
trigger('user.logged.in'); // calls 'user', 
                          //'user.logged' (the wildcard we want) and 
                          // 'user.logged.in'

Then, you could register the events user, user.logged and user.logged.in. And would effectively get a event hierarchy. With the rest of the event passed to the handler you could maybe do fun things too...


If you have your list of events in some sort of collection like this:

var events = ["user.logged.in", 
              "user.logged.out", 
              "user.disconnect", 
              "system.disconnect"
              // etc etc etc
             ];

Then, when an entity subscribes with "user.logged.*", you could do a comparison of the parts like this:

function subscribe(evt) {
    var evtParts = evt.split("."),
        eventParts, eventIdx, ii, subscribeTo = [];

    for (eventIdx = 0; eventIdx < events.length; eventIdx += 1) {
        eventParts = events[eventIdx].split(".");

        for (ii = 0; ii < eventParts.length && ii < evtParts.length; ii += 1) {
            if (evtParts[ii] == "*") {
                subscribeTo.push(events[eventIdx]);
            }
            else if (eventParts[ii] == evtParts[ii] && ii == evtParts.length - 1) {
                subscribeTo.push(events[eventIdx]);
            }
            else if (eventParts[ii] != evtParts[ii]) {
                break;
            }
        }
    }

    // Now, subscribeTo contains all the events that match evt, 
    // even when evt contains a wildcard.
}


A little late but you might take a look at EventEmitter2: https://github.com/asyncly/EventEmitter2

server.on('foo.*', function(value1, value2) {
  console.log(this.event, value1, value2);
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜