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:
In order to subscribe to an event the following is done:
In order to publish a message the following is done:
“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: