The Observer Pattern
Another pattern we reviewed earlier is the Observer (Publish/Subscribe) pattern. This is where the objects in a system may subscribe to other objects and be notified by them when an event of interest occurs.
jQuery core has come with built-in support for a Publish/Subscribe-like system for a few years now, which it refers to as custom events.
In earlier versions of the library, access to these custom events
was possible using jQuery.bind()
(subscribe), jQuery.trigger()
(publish), and jQuery.unbind()
(unsubscribe), but in recent versions, this can be done using jQuery.on(), jQuery.trigger(), and jQuery.off().
Here we can see an example of this being used in practice:
// Equivalent to subscribe(topicName, callback)$(document).on("topicName",function(){//..perform some behaviour});// Equivalent to publish(topicName)$(document).trigger("topicName");// Equivalent to unsubscribe(topicName)$(document).off("topicName");
Calls to jQuery.on() and jQuery.off() eventually go through the jQuery
events system. Similar to Ajax, as the implementation for this is
relatively long, we can instead look at where and how the actual event
handlers for custom events are attached:
jQuery.event={add:function(elem,types,handler,data,selector){varelemData,eventHandle,events,t,tns,type,namespaces,handleObj,handleObjIn,quick,handlers,special;...// Init the element's event structure and main handler,//if this is the firstevents=elemData.events ...