2 Copyright (c) 2010, Yahoo! Inc. All rights reserved.
3 Code licensed under the BSD License:
4 http://developer.yahoo.com/yui/license.html
8 YUI.add('history-base', function(Y) {
11 * Provides browser history management functionality using a simple
12 * add/replace/get paradigm. This can be used to ensure that the browser's back
13 * and forward buttons work as the user expects and to provide bookmarkable URLs
14 * that return the user to the current application state, even in an Ajax
15 * application that doesn't perform full-page refreshes.
22 * Provides global state management backed by an object, but with no browser
23 * history integration. For actual browser history integration and back/forward
24 * support, use the history-html5 or history-hash modules.
27 * @submodule history-base
31 * @param {Object} config (optional) configuration object, which may contain
32 * zero or more of the following properties:
35 * <dt>initialState (Object)</dt>
37 * Initial state to set, as an object hash of key/value pairs. This will be
38 * merged into the current global state.
45 GlobalEnv = YUI.namespace('Env.History'),
49 docMode = doc.documentMode,
52 DEFAULT_OPTIONS = {merge: true},
53 EVT_CHANGE = 'change',
55 SRC_REPLACE = 'replace';
57 function HistoryBase() {
58 this._init.apply(this, arguments);
61 Y.augment(HistoryBase, Y.EventTarget, null, null, {
68 if (!GlobalEnv._state) {
69 GlobalEnv._state = {};
72 // -- Private Methods ----------------------------------------------------------
75 * Returns <code>true</code> if <i>value</i> is a simple object and not a
76 * function or an array.
78 * @method _isSimpleObject
79 * @param {mixed} value
83 function _isSimpleObject(value) {
84 return Lang.type(value) === 'object';
87 // -- Public Static Properties -------------------------------------------------
90 * Name of this component.
96 HistoryBase.NAME = 'historyBase';
99 * Constant used to identify state changes originating from the
100 * <code>add()</code> method.
107 HistoryBase.SRC_ADD = SRC_ADD;
110 * Constant used to identify state changes originating from the
111 * <code>replace()</code> method.
113 * @property SRC_REPLACE
118 HistoryBase.SRC_REPLACE = SRC_REPLACE;
121 * Whether or not this browser supports the HTML5 History API.
128 // All HTML5-capable browsers except Gecko 2+ (Firefox 4+) correctly return
129 // true for 'onpopstate' in win. In order to support Gecko 2, we fall back to a
130 // UA sniff for now. (current as of Firefox 4.0b2)
131 HistoryBase.html5 = !!(win.history && win.history.pushState &&
132 win.history.replaceState && ('onpopstate' in win || Y.UA.gecko >= 2));
135 * Whether or not this browser supports the <code>window.onhashchange</code>
136 * event natively. Note that even if this is <code>true</code>, you may
137 * still want to use HistoryHash's synthetic <code>hashchange</code> event
138 * since it normalizes implementation differences and fixes spec violations
139 * across various browsers.
141 * @property nativeHashChange
146 // Most browsers that support hashchange expose it on the window. Opera 10.6+
147 // exposes it on the document (but you can still attach to it on the window).
149 // IE8 supports the hashchange event, but only in IE8 Standards
150 // Mode. However, IE8 in IE7 compatibility mode still defines the
151 // event but never fires it, so we can't just detect the event. We also can't
152 // just UA sniff for IE8, since other browsers support this event as well.
153 HistoryBase.nativeHashChange = ('onhashchange' in win || 'onhashchange' in doc) &&
154 (!docMode || docMode > 7);
156 Y.mix(HistoryBase.prototype, {
157 // -- Initialization -------------------------------------------------------
160 * Initializes this HistoryBase instance. This method is called by the
164 * @param {Object} config configuration object
167 _init: function (config) {
171 * Configuration object provided by the user on instantiation, or an
172 * empty object if one wasn't provided.
179 config = this._config = config || {};
182 * Resolved initial state: a merge of the user-supplied initial state
183 * (if any) and any initial state provided by a subclass. This may
184 * differ from <code>_config.initialState</code>. If neither the config
185 * nor a subclass supplies an initial state, this property will be
188 * @property _initialState
193 initialState = this._initialState = this._initialState ||
194 config.initialState || null;
197 * Fired when the state changes. To be notified of all state changes
198 * regardless of the History or YUI instance that generated them,
199 * subscribe to this event on <code>Y.Global</code>. If you would rather
200 * be notified only about changes generated by this specific History
201 * instance, subscribe to this event on the instance.
203 * @event history:change
204 * @param {EventFacade} e Event facade with the following additional
208 * <dt>changed (Object)</dt>
210 * Object hash of state items that have been added or changed. The
211 * key is the item key, and the value is an object containing
212 * <code>newVal</code> and <code>prevVal</code> properties
213 * representing the values of the item both before and after the
214 * change. If the item was newly added, <code>prevVal</code> will be
215 * <code>undefined</code>.
218 * <dt>newVal (Object)</dt>
220 * Object hash of key/value pairs of all state items after the
224 * <dt>prevVal (Object)</dt>
226 * Object hash of key/value pairs of all state items before the
230 * <dt>removed (Object)</dt>
232 * Object hash of key/value pairs of state items that have been
233 * removed. Values are the old values prior to removal.
236 * <dt>src (String)</dt>
238 * The source of the event. This can be used to selectively ignore
239 * events generated by certain sources.
243 this.publish(EVT_CHANGE, {
245 defaultFn: this._defChangeFn
248 // If initialState was provided, merge it into the current state.
250 this.add(initialState);
254 // -- Public Methods -------------------------------------------------------
257 * Adds a state entry with new values for the specified keys. By default,
258 * the new state will be merged into the existing state, and new values will
259 * override existing values. Specifying a <code>null</code> or
260 * <code>undefined</code> value will cause that key to be removed from the
264 * @param {Object} state Object hash of key/value pairs.
265 * @param {Object} options (optional) Zero or more of the following options:
267 * <dt>merge (Boolean)</dt>
270 * If <code>true</code> (the default), the new state will be merged
271 * into the existing state. New values will override existing values,
272 * and <code>null</code> or <code>undefined</code> values will be
273 * removed from the state.
277 * If <code>false</code>, the existing state will be discarded as a
278 * whole and the new state will take its place.
285 var args = YArray(arguments, 0, true);
286 args.unshift(SRC_ADD);
287 return this._change.apply(this, args);
291 * Adds a state entry with a new value for a single key. By default, the new
292 * value will be merged into the existing state values, and will override an
293 * existing value with the same key if there is one. Specifying a
294 * <code>null</code> or <code>undefined</code> value will cause the key to
295 * be removed from the new state entry.
298 * @param {String} key State parameter key.
299 * @param {String} value New value.
300 * @param {Object} options (optional) Zero or more options. See
301 * <code>add()</code> for a list of supported options.
304 addValue: function (key, value, options) {
307 return this._change(SRC_ADD, state, options);
311 * Returns the current value of the state parameter specified by <i>key</i>,
312 * or an object hash of key/value pairs for all current state parameters if
313 * no key is specified.
316 * @param {String} key (optional) State parameter key.
317 * @return {Object|String} Value of the specified state parameter, or an
318 * object hash of key/value pairs for all current state parameters.
320 get: function (key) {
321 var state = GlobalEnv._state,
322 isObject = _isSimpleObject(state);
325 return isObject && Obj.owns(state, key) ? state[key] : undefined;
327 return isObject ? Y.mix({}, state, true) : state; // mix provides a fast shallow clone.
332 * Same as <code>add()</code> except that a new browser history entry will
333 * not be created. Instead, the current history entry will be replaced with
337 * @param {Object} state Object hash of key/value pairs.
338 * @param {Object} options (optional) Zero or more options. See
339 * <code>add()</code> for a list of supported options.
342 replace: function () {
343 var args = YArray(arguments, 0, true);
344 args.unshift(SRC_REPLACE);
345 return this._change.apply(this, args);
349 * Same as <code>addValue()</code> except that a new browser history entry
350 * will not be created. Instead, the current history entry will be replaced
351 * with the new state.
353 * @method replaceValue
354 * @param {String} key State parameter key.
355 * @param {String} value New value.
356 * @param {Object} options (optional) Zero or more options. See
357 * <code>add()</code> for a list of supported options.
360 replaceValue: function (key, value, options) {
363 return this._change(SRC_REPLACE, state, options);
366 // -- Protected Methods ----------------------------------------------------
369 * Changes the state. This method provides a common implementation shared by
370 * the public methods for changing state.
373 * @param {String} src Source of the change, for inclusion in event facades
374 * to facilitate filtering.
375 * @param {Object} state Object hash of key/value pairs.
376 * @param {Object} options (optional) Zero or more options. See
377 * <code>add()</code> for a list of supported options.
381 _change: function (src, state, options) {
382 options = options ? Y.merge(DEFAULT_OPTIONS, options) : DEFAULT_OPTIONS;
384 if (options.merge && _isSimpleObject(state) &&
385 _isSimpleObject(GlobalEnv._state)) {
386 state = Y.merge(GlobalEnv._state, state);
389 this._resolveChanges(src, state, options);
394 * Called by _resolveChanges() when the state has changed. This method takes
395 * care of actually firing the necessary events.
397 * @method _fireEvents
398 * @param {String} src Source of the changes, for inclusion in event facades
399 * to facilitate filtering.
400 * @param {Object} changes Resolved changes.
401 * @param {Object} options Zero or more options. See <code>add()</code> for
402 * a list of supported options.
405 _fireEvents: function (src, changes, options) {
406 // Fire the global change event.
407 this.fire(EVT_CHANGE, {
409 changed : changes.changed,
410 newVal : changes.newState,
411 prevVal : changes.prevState,
412 removed : changes.removed,
416 // Fire change/remove events for individual items.
417 Obj.each(changes.changed, function (value, key) {
418 this._fireChangeEvent(src, key, value);
421 Obj.each(changes.removed, function (value, key) {
422 this._fireRemoveEvent(src, key, value);
427 * Fires a dynamic "[key]Change" event.
429 * @method _fireChangeEvent
430 * @param {String} src source of the change, for inclusion in event facades
431 * to facilitate filtering
432 * @param {String} key key of the item that was changed
433 * @param {Object} value object hash containing <i>newVal</i> and
434 * <i>prevVal</i> properties for the changed item
437 _fireChangeEvent: function (src, key, value) {
440 * Dynamic event fired when an individual history item is added or
441 * changed. The name of this event depends on the name of the key that
442 * changed. To listen to change events for a key named "foo", subscribe
443 * to the <code>fooChange</code> event; for a key named "bar", subscribe
444 * to <code>barChange</code>, etc.
448 * Key-specific events are only fired for instance-level changes; that
449 * is, changes that were made via the same History instance on which the
450 * event is subscribed. To be notified of changes made by other History
451 * instances, subscribe to the global <code>history:change</code> event.
455 * @param {EventFacade} e Event facade with the following additional
459 * <dt>newVal (mixed)</dt>
461 * The new value of the item after the change.
464 * <dt>prevVal (mixed)</dt>
466 * The previous value of the item before the change, or
467 * <code>undefined</code> if the item was just added and has no
471 * <dt>src (String)</dt>
473 * The source of the event. This can be used to selectively ignore
474 * events generated by certain sources.
478 this.fire(key + 'Change', {
479 newVal : value.newVal,
480 prevVal: value.prevVal,
486 * Fires a dynamic "[key]Remove" event.
488 * @method _fireRemoveEvent
489 * @param {String} src source of the change, for inclusion in event facades
490 * to facilitate filtering
491 * @param {String} key key of the item that was removed
492 * @param {mixed} value value of the item prior to its removal
495 _fireRemoveEvent: function (src, key, value) {
498 * Dynamic event fired when an individual history item is removed. The
499 * name of this event depends on the name of the key that was removed.
500 * To listen to remove events for a key named "foo", subscribe to the
501 * <code>fooRemove</code> event; for a key named "bar", subscribe to
502 * <code>barRemove</code>, etc.
506 * Key-specific events are only fired for instance-level changes; that
507 * is, changes that were made via the same History instance on which the
508 * event is subscribed. To be notified of changes made by other History
509 * instances, subscribe to the global <code>history:change</code> event.
513 * @param {EventFacade} e Event facade with the following additional
517 * <dt>prevVal (mixed)</dt>
519 * The value of the item before it was removed.
522 * <dt>src (String)</dt>
524 * The source of the event. This can be used to selectively ignore
525 * events generated by certain sources.
529 this.fire(key + 'Remove', {
536 * Resolves the changes (if any) between <i>newState</i> and the current
537 * state and fires appropriate events if things have changed.
539 * @method _resolveChanges
540 * @param {String} src source of the changes, for inclusion in event facades
541 * to facilitate filtering
542 * @param {Object} newState object hash of key/value pairs representing the
544 * @param {Object} options Zero or more options. See <code>add()</code> for
545 * a list of supported options.
548 _resolveChanges: function (src, newState, options) {
551 prevState = GlobalEnv._state,
562 if (_isSimpleObject(newState) && _isSimpleObject(prevState)) {
563 // Figure out what was added or changed.
564 Obj.each(newState, function (newVal, key) {
565 var prevVal = prevState[key];
567 if (newVal !== prevVal) {
577 // Figure out what was removed.
578 Obj.each(prevState, function (prevVal, key) {
579 if (!Obj.owns(newState, key) || newState[key] === null) {
580 delete newState[key];
581 removed[key] = prevVal;
586 isChanged = newState !== prevState;
590 this._fireEvents(src, {
593 prevState: prevState,
600 * Stores the specified state. Don't call this method directly; go through
601 * _resolveChanges() to ensure that changes are resolved and all events are
604 * @method _storeState
605 * @param {String} src source of the changes
606 * @param {Object} newState new state to store
607 * @param {Object} options Zero or more options. See <code>add()</code> for
608 * a list of supported options.
611 _storeState: function (src, newState) {
612 // Note: the src and options params aren't used here, but they are used
614 GlobalEnv._state = newState || {};
617 // -- Protected Event Handlers ---------------------------------------------
620 * Default <code>history:change</code> event handler.
622 * @method _defChangeFn
623 * @param {EventFacade} e state change event facade
626 _defChangeFn: function (e) {
627 this._storeState(e.src, e.newVal, e._options);
631 Y.HistoryBase = HistoryBase;
634 }, '3.3.0' ,{requires:['event-custom-complex']});