Pub/Sub with jQuery Callbacks and Deferred

https://api.jquery.com/jQuery.Callbacks/

by Patrick Hund

HTML

<div id="console"></div>

CSS

body {
    background-color: black;
}

#console {
    font-family: monospace;
    color: lime;
}

JavaScript

$(document).ready(function () {
    var topics = {};
    
    jQuery.Topic = function(id) {
        var callbacks, topic = id && topics[id], deferred = $.Deferred();
        if (!topic) {
            callbacks = jQuery.Callbacks();
            topic = {
                defer: function (method) {
                    deferred.done(method);
                },
                publish: function () {
                    callbacks.fire.apply(this, arguments);
                    deferred.resolve.apply(this, arguments);
                },
                subscribe: function (method) {
                    callbacks.add(method);
                    return this;
                },

                unsubscribe: function (method) {
                    callbacks.remove(method);
                    return this;
                }
            };
            if (id) {
                topics[id] = topic;
            }
        }
        return topic;
    };

    var print = function (text) {
        $("#console").append(text + "<br>");
    };
    
    var sendMail = function () {
        window.setTimeout(function () {
            $.Topic("mail arrived").publish("Oh klasse, ich freu mich!");
            $.Topic("mail arrived").publish("Oder nicht?");
        }, 3000);
    }
    
    $.Topic("mail arrived").defer(function (text) {
        print("FUUUUUUU! " + text);
    });
    
    $.Topic("mail arrived").subscribe(function (text) {
        print("hej! got mail: " + text);
    });
    
    sendMail();
    
    
    
    
    
    
});