Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$.event.trigger not firing in non-DOM object

var test = { }
$(test).on("testEvent", function (){
    console.log("testEvent has fired");
});
$.event.trigger("testEvent");

I am trying to using jQuery to do a publish/subscribe mechanism using events. I need to be able to attach events to non-DOM objects and be able to have them all fire from a single global trigger. I expected the code above to work but it did not result in the testEvent firing for the test object.

Note that there will be multiple objects in which an event will be subscribed to. A single $.event.trigger should fire all of those events.

Do note that this code works fine:

$('#someID').on("testEvent", function () {
console.log('testEvent has fired from DOM element');
})
$.event.trigger("testEvent");
like image 553
crv Avatar asked Apr 02 '12 13:04

crv


1 Answers

After doing some research it appears as though jQuery 1.7 provides an easy way to introduce a publish/subscribe mechanism. (found here) In order to have a publish/subscribe mechanism the following code can be used:

(function ($, window, undefined) {
    var topics = {};

    jQuery.Topic = function (id) {
        var callbacks, method, topic = id && topics[id];
        if (!topic) {
            callbacks = jQuery.Callbacks();
            topic = {
                publish: callbacks.fire,
                subscribe: callbacks.add,
                unsubscribe: callbacks.remove
            };
            if (id) {
                topics[id] = topic;
            }
        }
        return topic;
    };
})

In order to subscribe to an event the following is done:

$.Topic("message").subscribe(function () {
    console.log("a publish has occurred");
});

In order to publish a message the following is done:

$.Topic( "message" ).publish(data);

"Message" is the event name. The data argument contains any information you want passed to the subscribers.

In order to unsubscribe you must pass the function that was subscribed:

$.Topic( "message" ).unsubscribe(funcSubscribedToBefore);
like image 129
crv Avatar answered Sep 25 '22 14:09

crv