Using custom event namespacing

As a closing note for this chapter, we will present, in short, the mechanism that jQuery provides for namespacing custom events. The main benefit of event namespacing is that it allows us to use more specific event names that better describe their purpose, while also helping us to avoid conflicts between different implementation parts and plugins. It also provides a convenient way to unbind all the events of a given namespace from any target (element or broker).

A simple example implementation will look as follows:

var broker = $({}); broker.on('close.dialog', function (event, message){ console.log(event.type, event.namespace); }); broker.trigger('close.dialog', ['messageEmitted']); broker.off('.dialog'); // removes ...

Get jQuery Design Patterns now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.