jQuery in Action
The jQuery Event Model
101
Another little nifty event handling extra that jQuery provides for us is the ability
to group event handlers by assigning them to a namespace. Unlike conventional
namespacing (which assigns namespaces via a prefix), the event names are
namespaced by adding a suffix to the event name separated by a period character.
to group event handlers by assigning them to a namespace. Unlike conventional
namespacing (which assigns namespaces via a prefix), the event names are
namespaced by adding a suffix to the event name separated by a period character.
By grouping event bindings in this way, we can easily act upon them later as
a unit.
Take, for example, a page that has two modes: a display mode and an edit
mode. When in edit mode, event listeners are placed on many of the page ele-
ments, but these listeners are not appropriate for display mode and need to be
removed when the page transitions out of edit mode. We could namespace the
edit mode events with code such as
ments, but these listeners are not appropriate for display mode and need to be
removed when the page transitions out of edit mode. We could namespace the
edit mode events with code such as
$('#thing1').bind('click.editMode',someListener);
$('#thing2').bind('click.editMode',someOtherListener);
...
$('#thingN').bind('click.editMode',stillAnotherListener);
By grouping all these bindings into a namespace named
editMode
, we can later
operate upon them as a whole. For example, when the page leaves edit mode and
it comes time to remove all the bindings we could do this easily with
it comes time to remove all the bindings we could do this easily with
$('*').unbind('click.editMode');
This will remove all
click
bindings (the explanation of the
unbind()
method is com-
ing up in the next section) in the namespace
editMode
for all elements on the page.
Figure 4.7 The jQuery Event Model allows us to use a unified code base to support events in
Internet Explorer.
Internet Explorer.