API Docs for: 3.8.0
Show:

File: history/js/history-base.js

  1. /**
  2.  * Provides browser history management functionality using a simple
  3.  * add/replace/get paradigm. This can be used to ensure that the browser's back
  4.  * and forward buttons work as the user expects and to provide bookmarkable URLs
  5.  * that return the user to the current application state, even in an Ajax
  6.  * application that doesn't perform full-page refreshes.
  7.  *
  8.  * @module history
  9.  * @main history
  10.  * @since 3.2.0
  11.  */

  12. /**
  13.  * Provides global state management backed by an object, but with no browser
  14.  * history integration. For actual browser history integration and back/forward
  15.  * support, use the history-html5 or history-hash modules.
  16.  *
  17.  * @module history
  18.  * @submodule history-base
  19.  * @class HistoryBase
  20.  * @uses EventTarget
  21.  * @constructor
  22.  * @param {Object} config (optional) configuration object, which may contain
  23.  *   zero or more of the following properties:
  24.  *
  25.  * <dl>
  26.  *   <dt>force (Boolean)</dt>
  27.  *   <dd>
  28.  *     If `true`, a `history:change` event will be fired whenever the URL
  29.  *     changes, even if there is no associated state change. Default is `false`.
  30.  *   </dd>
  31.  *
  32.  *   <dt>initialState (Object)</dt>
  33.  *   <dd>
  34.  *     Initial state to set, as an object hash of key/value pairs. This will be
  35.  *     merged into the current global state.
  36.  *   </dd>
  37.  * </dl>
  38.  */

  39. var Lang      = Y.Lang,
  40.     Obj       = Y.Object,
  41.     GlobalEnv = YUI.namespace('Env.History'),
  42.     YArray    = Y.Array,

  43.     doc       = Y.config.doc,
  44.     docMode   = doc.documentMode,
  45.     win       = Y.config.win,

  46.     DEFAULT_OPTIONS = {merge: true},
  47.     EVT_CHANGE      = 'change',
  48.     SRC_ADD         = 'add',
  49.     SRC_REPLACE     = 'replace';

  50. function HistoryBase() {
  51.     this._init.apply(this, arguments);
  52. }

  53. Y.augment(HistoryBase, Y.EventTarget, null, null, {
  54.     emitFacade : true,
  55.     prefix     : 'history',
  56.     preventable: false,
  57.     queueable  : true
  58. });

  59. if (!GlobalEnv._state) {
  60.     GlobalEnv._state = {};
  61. }

  62. // -- Private Methods ----------------------------------------------------------

  63. /**
  64.  * Returns <code>true</code> if <i>value</i> is a simple object and not a
  65.  * function or an array.
  66.  *
  67.  * @method _isSimpleObject
  68.  * @param {mixed} value
  69.  * @return {Boolean}
  70.  * @private
  71.  */
  72. function _isSimpleObject(value) {
  73.     return Lang.type(value) === 'object';
  74. }

  75. // -- Public Static Properties -------------------------------------------------

  76. /**
  77.  * Name of this component.
  78.  *
  79.  * @property NAME
  80.  * @type String
  81.  * @static
  82.  */
  83. HistoryBase.NAME = 'historyBase';

  84. /**
  85.  * Constant used to identify state changes originating from the
  86.  * <code>add()</code> method.
  87.  *
  88.  * @property SRC_ADD
  89.  * @type String
  90.  * @static
  91.  * @final
  92.  */
  93. HistoryBase.SRC_ADD = SRC_ADD;

  94. /**
  95.  * Constant used to identify state changes originating from the
  96.  * <code>replace()</code> method.
  97.  *
  98.  * @property SRC_REPLACE
  99.  * @type String
  100.  * @static
  101.  * @final
  102.  */
  103. HistoryBase.SRC_REPLACE = SRC_REPLACE;

  104. /**
  105.  * Whether or not this browser supports the HTML5 History API.
  106.  *
  107.  * @property html5
  108.  * @type Boolean
  109.  * @static
  110.  */

  111. // All HTML5-capable browsers except Gecko 2+ (Firefox 4+) correctly return
  112. // true for 'onpopstate' in win. In order to support Gecko 2, we fall back to a
  113. // UA sniff for now. (current as of Firefox 4.0b2)
  114. HistoryBase.html5 = !!(win.history && win.history.pushState &&
  115.         win.history.replaceState && ('onpopstate' in win || Y.UA.gecko >= 2) &&
  116.         (!Y.UA.android || Y.UA.android >= 2.4));

  117. /**
  118.  * Whether or not this browser supports the <code>window.onhashchange</code>
  119.  * event natively. Note that even if this is <code>true</code>, you may
  120.  * still want to use HistoryHash's synthetic <code>hashchange</code> event
  121.  * since it normalizes implementation differences and fixes spec violations
  122.  * across various browsers.
  123.  *
  124.  * @property nativeHashChange
  125.  * @type Boolean
  126.  * @static
  127.  */

  128. // Most browsers that support hashchange expose it on the window. Opera 10.6+
  129. // exposes it on the document (but you can still attach to it on the window).
  130. //
  131. // IE8 supports the hashchange event, but only in IE8 Standards
  132. // Mode. However, IE8 in IE7 compatibility mode still defines the
  133. // event but never fires it, so we can't just detect the event. We also can't
  134. // just UA sniff for IE8, since other browsers support this event as well.
  135. HistoryBase.nativeHashChange = ('onhashchange' in win || 'onhashchange' in doc) &&
  136.         (!docMode || docMode > 7);

  137. Y.mix(HistoryBase.prototype, {
  138.     // -- Initialization -------------------------------------------------------

  139.     /**
  140.      * Initializes this HistoryBase instance. This method is called by the
  141.      * constructor.
  142.      *
  143.      * @method _init
  144.      * @param {Object} config configuration object
  145.      * @protected
  146.      */
  147.     _init: function (config) {
  148.         var initialState;

  149.         /**
  150.          * Configuration object provided by the user on instantiation, or an
  151.          * empty object if one wasn't provided.
  152.          *
  153.          * @property _config
  154.          * @type Object
  155.          * @default {}
  156.          * @protected
  157.          */
  158.         config = this._config = config || {};

  159.         /**
  160.          * If `true`, a `history:change` event will be fired whenever the URL
  161.          * changes, even if there is no associated state change.
  162.          *
  163.          * @property force
  164.          * @type Boolean
  165.          * @default false
  166.          */
  167.          this.force = !!config.force;

  168.         /**
  169.          * Resolved initial state: a merge of the user-supplied initial state
  170.          * (if any) and any initial state provided by a subclass. This may
  171.          * differ from <code>_config.initialState</code>. If neither the config
  172.          * nor a subclass supplies an initial state, this property will be
  173.          * <code>null</code>.
  174.          *
  175.          * @property _initialState
  176.          * @type Object|null
  177.          * @default {}
  178.          * @protected
  179.          */
  180.         initialState = this._initialState = this._initialState ||
  181.                 config.initialState || null;

  182.         /**
  183.          * Fired when the state changes. To be notified of all state changes
  184.          * regardless of the History or YUI instance that generated them,
  185.          * subscribe to this event on <code>Y.Global</code>. If you would rather
  186.          * be notified only about changes generated by this specific History
  187.          * instance, subscribe to this event on the instance.
  188.          *
  189.          * @event history:change
  190.          * @param {EventFacade} e Event facade with the following additional
  191.          *   properties:
  192.          *
  193.          * <dl>
  194.          *   <dt>changed (Object)</dt>
  195.          *   <dd>
  196.          *     Object hash of state items that have been added or changed. The
  197.          *     key is the item key, and the value is an object containing
  198.          *     <code>newVal</code> and <code>prevVal</code> properties
  199.          *     representing the values of the item both before and after the
  200.          *     change. If the item was newly added, <code>prevVal</code> will be
  201.          *     <code>undefined</code>.
  202.          *   </dd>
  203.          *
  204.          *   <dt>newVal (Object)</dt>
  205.          *   <dd>
  206.          *     Object hash of key/value pairs of all state items after the
  207.          *     change.
  208.          *   </dd>
  209.          *
  210.          *   <dt>prevVal (Object)</dt>
  211.          *   <dd>
  212.          *     Object hash of key/value pairs of all state items before the
  213.          *     change.
  214.          *   </dd>
  215.          *
  216.          *   <dt>removed (Object)</dt>
  217.          *   <dd>
  218.          *     Object hash of key/value pairs of state items that have been
  219.          *     removed. Values are the old values prior to removal.
  220.          *   </dd>
  221.          *
  222.          *   <dt>src (String)</dt>
  223.          *   <dd>
  224.          *     The source of the event. This can be used to selectively ignore
  225.          *     events generated by certain sources.
  226.          *   </dd>
  227.          * </dl>
  228.          */
  229.         this.publish(EVT_CHANGE, {
  230.             broadcast: 2,
  231.             defaultFn: this._defChangeFn
  232.         });

  233.         // If initialState was provided, merge it into the current state.
  234.         if (initialState) {
  235.             this.replace(initialState);
  236.         }
  237.     },

  238.     // -- Public Methods -------------------------------------------------------

  239.     /**
  240.      * Adds a state entry with new values for the specified keys. By default,
  241.      * the new state will be merged into the existing state, and new values will
  242.      * override existing values. Specifying a <code>null</code> or
  243.      * <code>undefined</code> value will cause that key to be removed from the
  244.      * new state entry.
  245.      *
  246.      * @method add
  247.      * @param {Object} state Object hash of key/value pairs.
  248.      * @param {Object} options (optional) Zero or more of the following options:
  249.      *   <dl>
  250.      *     <dt>merge (Boolean)</dt>
  251.      *     <dd>
  252.      *       <p>
  253.      *       If <code>true</code> (the default), the new state will be merged
  254.      *       into the existing state. New values will override existing values,
  255.      *       and <code>null</code> or <code>undefined</code> values will be
  256.      *       removed from the state.
  257.      *       </p>
  258.      *
  259.      *       <p>
  260.      *       If <code>false</code>, the existing state will be discarded as a
  261.      *       whole and the new state will take its place.
  262.      *       </p>
  263.      *     </dd>
  264.      *   </dl>
  265.      * @chainable
  266.      */
  267.     add: function () {
  268.         var args = YArray(arguments, 0, true);
  269.         args.unshift(SRC_ADD);
  270.         return this._change.apply(this, args);
  271.     },

  272.     /**
  273.      * Adds a state entry with a new value for a single key. By default, the new
  274.      * value will be merged into the existing state values, and will override an
  275.      * existing value with the same key if there is one. Specifying a
  276.      * <code>null</code> or <code>undefined</code> value will cause the key to
  277.      * be removed from the new state entry.
  278.      *
  279.      * @method addValue
  280.      * @param {String} key State parameter key.
  281.      * @param {String} value New value.
  282.      * @param {Object} options (optional) Zero or more options. See
  283.      *   <code>add()</code> for a list of supported options.
  284.      * @chainable
  285.      */
  286.     addValue: function (key, value, options) {
  287.         var state = {};
  288.         state[key] = value;
  289.         return this._change(SRC_ADD, state, options);
  290.     },

  291.     /**
  292.      * Returns the current value of the state parameter specified by <i>key</i>,
  293.      * or an object hash of key/value pairs for all current state parameters if
  294.      * no key is specified.
  295.      *
  296.      * @method get
  297.      * @param {String} key (optional) State parameter key.
  298.      * @return {Object|String} Value of the specified state parameter, or an
  299.      *   object hash of key/value pairs for all current state parameters.
  300.      */
  301.     get: function (key) {
  302.         var state    = GlobalEnv._state,
  303.             isObject = _isSimpleObject(state);

  304.         if (key) {
  305.             return isObject && Obj.owns(state, key) ? state[key] : undefined;
  306.         } else {
  307.             return isObject ? Y.mix({}, state, true) : state; // mix provides a fast shallow clone.
  308.         }
  309.     },

  310.     /**
  311.      * Same as <code>add()</code> except that a new browser history entry will
  312.      * not be created. Instead, the current history entry will be replaced with
  313.      * the new state.
  314.      *
  315.      * @method replace
  316.      * @param {Object} state Object hash of key/value pairs.
  317.      * @param {Object} options (optional) Zero or more options. See
  318.      *   <code>add()</code> for a list of supported options.
  319.      * @chainable
  320.      */
  321.     replace: function () {
  322.         var args = YArray(arguments, 0, true);
  323.         args.unshift(SRC_REPLACE);
  324.         return this._change.apply(this, args);
  325.     },

  326.     /**
  327.      * Same as <code>addValue()</code> except that a new browser history entry
  328.      * will not be created. Instead, the current history entry will be replaced
  329.      * with the new state.
  330.      *
  331.      * @method replaceValue
  332.      * @param {String} key State parameter key.
  333.      * @param {String} value New value.
  334.      * @param {Object} options (optional) Zero or more options. See
  335.      *   <code>add()</code> for a list of supported options.
  336.      * @chainable
  337.      */
  338.     replaceValue: function (key, value, options) {
  339.         var state = {};
  340.         state[key] = value;
  341.         return this._change(SRC_REPLACE, state, options);
  342.     },

  343.     // -- Protected Methods ----------------------------------------------------

  344.     /**
  345.      * Changes the state. This method provides a common implementation shared by
  346.      * the public methods for changing state.
  347.      *
  348.      * @method _change
  349.      * @param {String} src Source of the change, for inclusion in event facades
  350.      *   to facilitate filtering.
  351.      * @param {Object} state Object hash of key/value pairs.
  352.      * @param {Object} options (optional) Zero or more options. See
  353.      *   <code>add()</code> for a list of supported options.
  354.      * @protected
  355.      * @chainable
  356.      */
  357.     _change: function (src, state, options) {
  358.         options = options ? Y.merge(DEFAULT_OPTIONS, options) : DEFAULT_OPTIONS;

  359.         if (options.merge && _isSimpleObject(state) &&
  360.                 _isSimpleObject(GlobalEnv._state)) {
  361.             state = Y.merge(GlobalEnv._state, state);
  362.         }

  363.         this._resolveChanges(src, state, options);
  364.         return this;
  365.     },

  366.     /**
  367.      * Called by _resolveChanges() when the state has changed. This method takes
  368.      * care of actually firing the necessary events.
  369.      *
  370.      * @method _fireEvents
  371.      * @param {String} src Source of the changes, for inclusion in event facades
  372.      *   to facilitate filtering.
  373.      * @param {Object} changes Resolved changes.
  374.      * @param {Object} options Zero or more options. See <code>add()</code> for
  375.      *   a list of supported options.
  376.      * @protected
  377.      */
  378.     _fireEvents: function (src, changes, options) {
  379.         // Fire the global change event.
  380.         this.fire(EVT_CHANGE, {
  381.             _options: options,
  382.             changed : changes.changed,
  383.             newVal  : changes.newState,
  384.             prevVal : changes.prevState,
  385.             removed : changes.removed,
  386.             src     : src
  387.         });

  388.         // Fire change/remove events for individual items.
  389.         Obj.each(changes.changed, function (value, key) {
  390.             this._fireChangeEvent(src, key, value);
  391.         }, this);

  392.         Obj.each(changes.removed, function (value, key) {
  393.             this._fireRemoveEvent(src, key, value);
  394.         }, this);
  395.     },

  396.     /**
  397.      * Fires a dynamic "[key]Change" event.
  398.      *
  399.      * @method _fireChangeEvent
  400.      * @param {String} src source of the change, for inclusion in event facades
  401.      *   to facilitate filtering
  402.      * @param {String} key key of the item that was changed
  403.      * @param {Object} value object hash containing <i>newVal</i> and
  404.      *   <i>prevVal</i> properties for the changed item
  405.      * @protected
  406.      */
  407.     _fireChangeEvent: function (src, key, value) {
  408.         /**
  409.          * <p>
  410.          * Dynamic event fired when an individual history item is added or
  411.          * changed. The name of this event depends on the name of the key that
  412.          * changed. To listen to change events for a key named "foo", subscribe
  413.          * to the <code>fooChange</code> event; for a key named "bar", subscribe
  414.          * to <code>barChange</code>, etc.
  415.          * </p>
  416.          *
  417.          * <p>
  418.          * Key-specific events are only fired for instance-level changes; that
  419.          * is, changes that were made via the same History instance on which the
  420.          * event is subscribed. To be notified of changes made by other History
  421.          * instances, subscribe to the global <code>history:change</code> event.
  422.          * </p>
  423.          *
  424.          * @event [key]Change
  425.          * @param {EventFacade} e Event facade with the following additional
  426.          *   properties:
  427.          *
  428.          * <dl>
  429.          *   <dt>newVal (mixed)</dt>
  430.          *   <dd>
  431.          *     The new value of the item after the change.
  432.          *   </dd>
  433.          *
  434.          *   <dt>prevVal (mixed)</dt>
  435.          *   <dd>
  436.          *     The previous value of the item before the change, or
  437.          *     <code>undefined</code> if the item was just added and has no
  438.          *     previous value.
  439.          *   </dd>
  440.          *
  441.          *   <dt>src (String)</dt>
  442.          *   <dd>
  443.          *     The source of the event. This can be used to selectively ignore
  444.          *     events generated by certain sources.
  445.          *   </dd>
  446.          * </dl>
  447.          */
  448.         this.fire(key + 'Change', {
  449.             newVal : value.newVal,
  450.             prevVal: value.prevVal,
  451.             src    : src
  452.         });
  453.     },

  454.     /**
  455.      * Fires a dynamic "[key]Remove" event.
  456.      *
  457.      * @method _fireRemoveEvent
  458.      * @param {String} src source of the change, for inclusion in event facades
  459.      *   to facilitate filtering
  460.      * @param {String} key key of the item that was removed
  461.      * @param {mixed} value value of the item prior to its removal
  462.      * @protected
  463.      */
  464.     _fireRemoveEvent: function (src, key, value) {
  465.         /**
  466.          * <p>
  467.          * Dynamic event fired when an individual history item is removed. The
  468.          * name of this event depends on the name of the key that was removed.
  469.          * To listen to remove events for a key named "foo", subscribe to the
  470.          * <code>fooRemove</code> event; for a key named "bar", subscribe to
  471.          * <code>barRemove</code>, etc.
  472.          * </p>
  473.          *
  474.          * <p>
  475.          * Key-specific events are only fired for instance-level changes; that
  476.          * is, changes that were made via the same History instance on which the
  477.          * event is subscribed. To be notified of changes made by other History
  478.          * instances, subscribe to the global <code>history:change</code> event.
  479.          * </p>
  480.          *
  481.          * @event [key]Remove
  482.          * @param {EventFacade} e Event facade with the following additional
  483.          *   properties:
  484.          *
  485.          * <dl>
  486.          *   <dt>prevVal (mixed)</dt>
  487.          *   <dd>
  488.          *     The value of the item before it was removed.
  489.          *   </dd>
  490.          *
  491.          *   <dt>src (String)</dt>
  492.          *   <dd>
  493.          *     The source of the event. This can be used to selectively ignore
  494.          *     events generated by certain sources.
  495.          *   </dd>
  496.          * </dl>
  497.          */
  498.         this.fire(key + 'Remove', {
  499.             prevVal: value,
  500.             src    : src
  501.         });
  502.     },

  503.     /**
  504.      * Resolves the changes (if any) between <i>newState</i> and the current
  505.      * state and fires appropriate events if things have changed.
  506.      *
  507.      * @method _resolveChanges
  508.      * @param {String} src source of the changes, for inclusion in event facades
  509.      *   to facilitate filtering
  510.      * @param {Object} newState object hash of key/value pairs representing the
  511.      *   new state
  512.      * @param {Object} options Zero or more options. See <code>add()</code> for
  513.      *   a list of supported options.
  514.      * @protected
  515.      */
  516.     _resolveChanges: function (src, newState, options) {
  517.         var changed   = {},
  518.             isChanged,
  519.             prevState = GlobalEnv._state,
  520.             removed   = {};

  521.         newState || (newState = {});
  522.         options  || (options  = {});

  523.         if (_isSimpleObject(newState) && _isSimpleObject(prevState)) {
  524.             // Figure out what was added or changed.
  525.             Obj.each(newState, function (newVal, key) {
  526.                 var prevVal = prevState[key];

  527.                 if (newVal !== prevVal) {
  528.                     changed[key] = {
  529.                         newVal : newVal,
  530.                         prevVal: prevVal
  531.                     };

  532.                     isChanged = true;
  533.                 }
  534.             }, this);

  535.             // Figure out what was removed.
  536.             Obj.each(prevState, function (prevVal, key) {
  537.                 if (!Obj.owns(newState, key) || newState[key] === null) {
  538.                     delete newState[key];
  539.                     removed[key] = prevVal;
  540.                     isChanged = true;
  541.                 }
  542.             }, this);
  543.         } else {
  544.             isChanged = newState !== prevState;
  545.         }

  546.         if (isChanged || this.force) {
  547.             this._fireEvents(src, {
  548.                 changed  : changed,
  549.                 newState : newState,
  550.                 prevState: prevState,
  551.                 removed  : removed
  552.             }, options);
  553.         }
  554.     },

  555.     /**
  556.      * Stores the specified state. Don't call this method directly; go through
  557.      * _resolveChanges() to ensure that changes are resolved and all events are
  558.      * fired properly.
  559.      *
  560.      * @method _storeState
  561.      * @param {String} src source of the changes
  562.      * @param {Object} newState new state to store
  563.      * @param {Object} options Zero or more options. See <code>add()</code> for
  564.      *   a list of supported options.
  565.      * @protected
  566.      */
  567.     _storeState: function (src, newState) {
  568.         // Note: the src and options params aren't used here, but they are used
  569.         // by subclasses.
  570.         GlobalEnv._state = newState || {};
  571.     },

  572.     // -- Protected Event Handlers ---------------------------------------------

  573.     /**
  574.      * Default <code>history:change</code> event handler.
  575.      *
  576.      * @method _defChangeFn
  577.      * @param {EventFacade} e state change event facade
  578.      * @protected
  579.      */
  580.     _defChangeFn: function (e) {
  581.         this._storeState(e.src, e.newVal, e._options);
  582.     }
  583. }, true);

  584. Y.HistoryBase = HistoryBase;

  585.