Search code examples
javascriptpublish-subscribeobserver-pattern

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 subscribe function i should check the passed event type for wildcards and subscribe to both events?


Solution

  • 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...