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");
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With