Om3ga
Om3ga

Reputation: 32863

pub/sub API does not work

I wrote following code to implement simple pub/sub API.

(function ($) {
    var o = $({});

    $.each({
        trigger: 'trigger',
        on: 'listen',
        off: 'stopListen'
    }, function (key, val) {
        jQuery[val] = function () {
            //console.log(o[key]);
            o[key].apply(o, arguments);
        }
    });
})(jQuery);

$.trigger('watch');

$.listen('watch', function (e, data) {
    alert('Watch it');
});

However, above code does not alert Watch it. Why it does not work and how can I fix it?

Upvotes: 0

Views: 144

Answers (1)

Saravana
Saravana

Reputation: 40594

You have to listen to the event before you trigger it. Try executing in this order:

$.listen('watch', function (e, data) {
    alert('Watch it');
});

$.trigger('watch');

Upvotes: 2

Related Questions