Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

Lesson 2: Handling storage events CHAPTER 15 567


Bubbling and canceling events
Unlike some other types of events, the storage event cannot be canceled from within a
callback; it’s simply a means for informing subscribers when a change occurs. It also does not
bubble up like other events.

Subscribing to events


To begin listening for event notifications, add an event handler to the storage event as
follows.
function respondToChange(e) {
alert(e.newValue);
}
window.addEventListener('storage', respondToChange, false);

To trigger this event, perform an operation like the following in a new tab within the same
site.
localStorage.setItem('name', 'Glenn');

Considering Internet Explorer 8 performance with storage events
Storage events are only partially supported in Internet Explorer 8, so if you need to support
that specific browser version, consider these factors.
■■Only the url property is implemented on the StorageEvent object. The rest of the prop-
erties will return null.
■■The storage event itself is not triggered on the window object as it is in browsers that
are more current; instead, it is triggered on the document object.
■■The addEventListener() method is not available, but you can use the attachEvent()
method.
The following example subscribes to storage changes while safeguarding against when
Internet Explorer 8 might be used.
if (window.addEventListener) { // check for IE8
window.addEventListener('storage', respondToChange, false);
} else {
document.attachEvent('onstorage', respondToChange);
}

Binding to storage events by using jQuery
An alternative method to using addEventListener() for your subscriptions is to use the event-
binding features jQuery provides. You have to update your respondToChange() method
because it will now return a different event that actually wraps the raw event you were work-
ing with in the previous example.
function respondToChange(e) {
Free download pdf