Make WordPress Core

Changeset 63454


Ignore:
Timestamp:
09/03/2026 10:59:40 PM (2 months ago)
Author:
westonruter
Message:

Customize: Document and modernize the JS base API.

The variadic signatures could not be documented without names for their arguments, so the arguments object is replaced with modern rest parameters across wp.customize.Class, Events, Value, Values, Element and Messenger. The Array.prototype.slice alias they relied on is no longer needed and is removed. Rest parameters are supported by >96% of users globally and all browser versions supported by WordPress.

The argument these two files receive was named exports, while the docblock beside the line using it said window.wp.customize. It is now wp, and the arguments of both wrapping functions are documented.

Many of the types named nothing that resolves. Seven tags were typed mixed, which is not a JSDoc type; one still carried the [type] placeholder an IDE had left behind; and one each read ..., an unqualified Value, and string|jQuery collection, which is two words rather than a type expression. Where the jQuery namespace appeared it was spelled in lower case, so it named the $ function rather than a collection or an event. The value accepted by Value#set() was typed as an object, though a Value holds anything. In loader.js the one documented parameter had no braces at all.

The remaining docblocks are new, since most of these methods carried none. Among what they now record: Class returns a function rather than an object whenever the prototype defines an instance method, which is how wp.customize() and wp.customize.control() come to be callable, and Value#link() binds the receiver to follow the values it is given rather than the reverse.

QUnit tests cover the applicator form of the constructor, the forwarding of arguments through the event methods, and unsync() in both directions, resolving two long-standing todos in that file.

Developed as subset of ​https://github.com/WordPress/wordpress-develop/pull/10743.
Follow-up to r48110, r48650.

Props westonruter, afercia, grapplerulrich, vishalkakadiya, shailu25.
See #39671, #40831, #64662, #66033.

Location:
trunk
Files:
3 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/js/_enqueues/wp/customize/base.js

    r55843 r63454  
    66window.wp = window.wp || {};
    77
    8 (function( exports, $ ){
    9         var api = {}, ctor, inherits,
    10                 slice = Array.prototype.slice;
     8/**
     9 * @param {Object}       wp The WordPress global object.
     10 * @param {JQueryStatic} $  The jQuery object.
     11 */
     12(function( wp, $ ){
     13        var api = {}, ctor, inherits;
    1114
    1215        // Shared empty constructor function to aid in prototype-chain creation.
    … …  
    1821         * class properties to be extended.
    1922         *
    20          * @param object parent      Parent class constructor to inherit from.
    21          * @param object protoProps  Properties to apply to the prototype for use as class instance properties.
    22          * @param object staticProps Properties to apply directly to the class constructor.
    23          * @return child The subclassed constructor.
     23         * @param {Object} parent        Parent class constructor to inherit from.
     24         * @param {Object} [protoProps]  Properties to apply to the prototype for use as class instance properties.
     25         * @param {Object} [staticProps] Properties to apply directly to the class constructor.
     26         * @return {Function} The subclassed constructor.
    2427         */
    2528        inherits = function( parent, protoProps, staticProps ) {
    … …  
    3437                        child = protoProps.constructor;
    3538                } else {
    36                         child = function() {
     39                        child = function( ...args ) {
    3740                                /*
    3841                                 * Storing the result `super()` before returning the value
    … …  
    4144                                 * the original object. This causes all sorts of trouble.
    4245                                 */
    43                                 var result = parent.apply( this, arguments );
     46                                var result = parent.apply( this, args );
    4447                                return result;
    4548                        };
    … …  
    7679        /**
    7780         * Base class for object inheritance.
    78          */
    79         api.Class = function( applicator, argsArray, options ) {
    80                 var magic, args = arguments;
    81 
    82                 if ( applicator && argsArray && api.Class.applicator === applicator ) {
    83                         args = argsArray;
    84                         $.extend( this, options || {} );
     81         *
     82         * The arguments are normally passed straight through to the class's
     83         * initialize method. As a special case, when the first argument is
     84         * api.Class.applicator, the second argument is used as the array of
     85         * arguments for initialize and the third is used to extend the instance.
     86         * This allows a class to be constructed from an argument list that is only
     87         * known at runtime. See {@link wp.customize.Values#create}.
     88         *
     89         * @param {...*} args Arguments for the class's initialize method. Or
     90         *                    api.Class.applicator, followed by the array of
     91         *                    arguments for the initialize method, followed by an
     92         *                    optional object of properties to extend the instance
     93         *                    with.
     94         * @return {Object|Function} The instance of the class, which is a function when the class
     95         *                           defines an instance method, so that the instance is callable.
     96         */
     97        api.Class = function( ...args ) {
     98                var magic;
     99
     100                if ( args[0] && args[1] && api.Class.applicator === args[0] ) {
     101                        $.extend( this, args[2] || {} );
     102                        args = args[1];
    85103                }
    86104
    … …  
    95113                 */
    96114                if ( this.instance ) {
    97                         magic = function() {
    98                                 return magic.instance.apply( magic, arguments );
     115                        magic = function( ...instanceArgs ) {
     116                                return magic.instance.apply( magic, instanceArgs );
    99117                        };
    100118
    … …  
    109127         * Creates a subclass of the class.
    110128         *
    111          * @param object protoProps  Properties to apply to the prototype.
    112          * @param object staticProps Properties to apply directly to the class.
    113          * @return child The subclass.
     129         * @param {Object} [protoProps]  Properties to apply to the prototype.
     130         * @param {Object} [staticProps] Properties to apply directly to the class.
     131         * @return {Function} The subclass.
    114132         */
    115133        api.Class.extend = function( protoProps, staticProps ) {
    … …  
    156174         */
    157175        api.Events = {
    158                 trigger: function( id ) {
     176                /**
     177                 * Trigger an event, invoking all of the callbacks bound to it.
     178                 *
     179                 * @param {string} id     ID of the event to trigger.
     180                 * @param {...*}   [args] Zero or more arguments to pass to the bound callbacks.
     181                 * @return {Object} The instance the mixin is applied to.
     182                 */
     183                trigger: function( id, ...args ) {
    159184                        if ( this.topics && this.topics[ id ] ) {
    160                                 this.topics[ id ].fireWith( this, slice.call( arguments, 1 ) );
    161                         }
    162                         return this;
    163                 },
    164 
    165                 bind: function( id ) {
     185                                this.topics[ id ].fireWith( this, args );
     186                        }
     187                        return this;
     188                },
     189
     190                /**
     191                 * Bind one or more callbacks to an event.
     192                 *
     193                 * @param {string}      id        ID of the event to bind to.
     194                 * @param {...Function} callbacks A function, or multiple functions, to add to the callback stack.
     195                 * @return {Object} The instance the mixin is applied to.
     196                 */
     197                bind: function( id, ...callbacks ) {
    166198                        this.topics = this.topics || {};
    167199                        this.topics[ id ] = this.topics[ id ] || $.Callbacks();
    168                         this.topics[ id ].add.apply( this.topics[ id ], slice.call( arguments, 1 ) );
    169                         return this;
    170                 },
    171 
    172                 unbind: function( id ) {
     200                        this.topics[ id ].add.apply( this.topics[ id ], callbacks );
     201                        return this;
     202                },
     203
     204                /**
     205                 * Unbind one or more previously bound callbacks from an event.
     206                 *
     207                 * @param {string}      id        ID of the event to unbind from.
     208                 * @param {...Function} callbacks A function, or multiple functions, to remove from the callback stack.
     209                 * @return {Object} The instance the mixin is applied to.
     210                 */
     211                unbind: function( id, ...callbacks ) {
    173212                        if ( this.topics && this.topics[ id ] ) {
    174                                 this.topics[ id ].remove.apply( this.topics[ id ], slice.call( arguments, 1 ) );
     213                                this.topics[ id ].remove.apply( this.topics[ id ], callbacks );
    175214                        }
    176215                        return this;
    … …  
    184223         * @alias wp.customize.Value
    185224         *
    186          * @constructor
     225         * @class
     226         * @augments wp.customize.Class
    187227         */
    188228        api.Value = api.Class.extend(/** @lends wp.customize.Value.prototype */{
    189229                /**
    190                  * @param {mixed}  initial The initial value.
    191                  * @param {Object} options
     230                 * @param {*}      initial  The initial value.
     231                 * @param {Object} [options] Options to extend the instance with.
    192232                 */
    193233                initialize: function( initial, options ) {
    … …  
    205245                 * Set to null to prevent the instance from extending a function.
    206246                 */
    207                 instance: function() {
    208                         return arguments.length ? this.set.apply( this, arguments ) : this.get();
     247                instance: function( ...args ) {
     248                        return args.length ? this.set.apply( this, args ) : this.get();
    209249                },
    210250
    … …  
    212252                 * Get the value.
    213253                 *
    214                  * @return {mixed}
     254                 * @return {*} The value.
    215255                 */
    216256                get: function() {
    … …  
    221261                 * Set the value and trigger all bound callbacks.
    222262                 *
    223                  * @param {Object} to New value.
    224                  */
    225                 set: function( to ) {
     263                 * @param {*}    to     New value.
     264                 * @param {...*} [args] Zero or more additional arguments to pass to the setter.
     265                 * @return {wp.customize.Value} The instance of the Value.
     266                 */
     267                set: function( to, ...args ) {
    226268                        var from = this._value;
    227269
    228                         to = this._setter.apply( this, arguments );
     270                        to = this._setter( to, ...args );
    229271                        to = this.validate( to );
    230272
    … …  
    268310                 * Bind a function to be invoked whenever the value changes.
    269311                 *
    270                  * @param {...Function} A function, or multiple functions, to add to the callback stack.
    271                  */
    272                 bind: function() {
    273                         this.callbacks.add.apply( this.callbacks, arguments );
     312                 * @param {...Function} callbacks A function, or multiple functions, to add to the callback stack.
     313                 * @return {wp.customize.Value} The instance of the Value.
     314                 */
     315                bind: function( ...callbacks ) {
     316                        this.callbacks.add.apply( this.callbacks, callbacks );
    274317                        return this;
    275318                },
    … …  
    278321                 * Unbind a previously bound function.
    279322                 *
    280                  * @param {...Function} A function, or multiple functions, to remove from the callback stack.
    281                  */
    282                 unbind: function() {
    283                         this.callbacks.remove.apply( this.callbacks, arguments );
    284                         return this;
    285                 },
    286 
    287                 link: function() { // values*
     323                 * @param {...Function} callbacks A function, or multiple functions, to remove from the callback stack.
     324                 * @return {wp.customize.Value} The instance of the Value.
     325                 */
     326                unbind: function( ...callbacks ) {
     327                        this.callbacks.remove.apply( this.callbacks, callbacks );
     328                        return this;
     329                },
     330
     331                /**
     332                 * Update this value whenever one or more other values change.
     333                 *
     334                 * Note that this is one-directional: this value follows the supplied
     335                 * values, not the other way around. Use sync() to link in both
     336                 * directions.
     337                 *
     338                 * @param {...wp.customize.Value} values A value, or multiple values, for this value to follow.
     339                 * @return {wp.customize.Value} The instance of the Value.
     340                 */
     341                link: function( ...values ) {
    288342                        var set = this.set;
    289                         $.each( arguments, function() {
     343                        $.each( values, function() {
    290344                                this.bind( set );
    291345                        });
    … …  
    293347                },
    294348
    295                 unlink: function() { // values*
     349                /**
     350                 * Stop updating this value when one or more other values change.
     351                 *
     352                 * @param {...wp.customize.Value} values A value, or multiple values, for this value to stop following.
     353                 * @return {wp.customize.Value} The instance of the Value.
     354                 */
     355                unlink: function( ...values ) {
    296356                        var set = this.set;
    297                         $.each( arguments, function() {
     357                        $.each( values, function() {
    298358                                this.unbind( set );
    299359                        });
    … …  
    301361                },
    302362
    303                 sync: function() { // values*
     363                /**
     364                 * Link this value with one or more other values in both directions.
     365                 *
     366                 * @param {...wp.customize.Value} values A value, or multiple values, to keep in sync with this value.
     367                 * @return {wp.customize.Value} The instance of the Value.
     368                 */
     369                sync: function( ...values ) {
    304370                        var that = this;
    305                         $.each( arguments, function() {
     371                        $.each( values, function() {
    306372                                that.link( this );
    307373                                this.link( that );
    … …  
    310376                },
    311377
    312                 unsync: function() { // values*
     378                /**
     379                 * Stop keeping this value in sync with one or more other values.
     380                 *
     381                 * @param {...wp.customize.Value} values A value, or multiple values, to stop keeping in sync with this value.
     382                 * @return {wp.customize.Value} The instance of the Value.
     383                 */
     384                unsync: function( ...values ) {
    313385                        var that = this;
    314                         $.each( arguments, function() {
     386                        $.each( values, function() {
    315387                                that.unlink( this );
    316388                                this.unlink( that );
    … …  
    326398         * @alias wp.customize.Values
    327399         *
    328          * @constructor
     400         * @class
    329401         * @augments wp.customize.Class
    330402         * @mixes wp.customize.Events
    … …  
    335407                 * The default constructor for items of the collection.
    336408                 *
    337                  * @type {object}
     409                 * @type {Function}
    338410                 */
    339411                defaultConstructor: api.Value,
    … …  
    353425                 * items are available.
    354426                 *
    355                  * @see {api.Values.when}
    356                  *
    357                  * @param {string} id ID of the item.
    358                  * @param {...}      Zero or more IDs of items to wait for and a callback
    359                  *                    function to invoke when they're available. Optional.
    360                  * @return {mixed} The item instance if only one ID was supplied.
    361                  *                 A Deferred Promise object if a callback function is supplied.
    362                  */
    363                 instance: function( id ) {
    364                         if ( arguments.length === 1 ) {
     427                 * @see {@link wp.customize.Values#when}
     428                 *
     429                 * @param {string}               id    ID of the item.
     430                 * @param {...(string|Function)} [args] Zero or more IDs of items to wait for and a callback
     431                 *                                      function to invoke when they're available. Optional.
     432                 * @return {*} The item instance if only one ID was supplied.
     433                 *             A Deferred Promise object if a callback function is supplied.
     434                 */
     435                instance: function( id, ...args ) {
     436                        if ( 0 === args.length ) {
    365437                                return this.value( id );
    366438                        }
    367439
    368                         return this.when.apply( this, arguments );
     440                        return this.when( id, ...args );
    369441                },
    370442
    … …  
    373445                 *
    374446                 * @param {string} id The ID of the item.
    375                  * @return {[type]} [description]
     447                 * @return {*} The item instance.
    376448                 */
    377449                value: function( id ) {
    … …  
    383455                 *
    384456                 * @param {string} id The ID of the item to look for.
    385                  * @return {boolean}
     457                 * @return {boolean} True if the collection has an item with the given ID, false otherwise.
    386458                 */
    387459                has: function( id ) {
    … …  
    392464                 * Add an item to the collection.
    393465                 *
    394                  * @param {string|wp.customize.Class} item         - The item instance to add, or the ID for the instance to add.
    395                  *                                                   When an ID string is supplied, then itemObject must be provided.
    396                  * @param {wp.customize.Class}        [itemObject] - The item instance when the first argument is an ID string.
     466                 * @param {string|wp.customize.Class} item         The item instance to add, or the ID for the instance to add.
     467                 *                                                 When an ID string is supplied, then itemObject must be provided.
     468                 * @param {wp.customize.Class}        [itemObject] The item instance when the first argument is an ID string.
    397469                 * @return {wp.customize.Class} The new item's instance, or an existing instance if already added.
    398470                 */
    … …  
    437509                 * and store it in the collection.
    438510                 *
    439                  * @param {string} id    The ID of the item.
    440                  * @param {mixed}  value Any extra arguments are passed into the item's initialize method.
    441                  * @return {mixed} The new item's instance.
    442                  */
    443                 create: function( id ) {
    444                         return this.add( id, new this.defaultConstructor( api.Class.applicator, slice.call( arguments, 1 ) ) );
     511                 * @param {string} id     The ID of the item.
     512                 * @param {...*}   [args] Zero or more extra arguments to pass into the item's initialize method.
     513                 * @return {wp.customize.Class} The new item's instance.
     514                 */
     515                create: function( id, ...args ) {
     516                        return this.add( id, new this.defaultConstructor( api.Class.applicator, args ) );
    445517                },
    446518
    … …  
    448520                 * Iterate over all items in the collection invoking the provided callback.
    449521                 *
    450                  * @param {Function} callback Function to invoke.
    451                  * @param {Object}   context  Object context to invoke the function with. Optional.
     522                 * @param {Function} callback  Function to invoke.
     523                 * @param {Object}   [context] Object context to invoke the function with.
    452524                 */
    453525                each: function( callback, context ) {
    … …  
    495567                 *     when( id1, id2, id3, function( value1, value2, value3 ) {} );
    496568                 *
    497                  * @return $.Deferred.promise();
    498                  */
    499                 when: function() {
     569                 * @param {...(string|Function)} ids Zero or more IDs of items to wait for, optionally followed by
     570                 *                                   a callback function to invoke once they are all available.
     571                 * @return {JQuery.Promise<*>} A promise that is resolved when all of the requested values exist.
     572                 */
     573                when: function( ...ids ) {
    500574                        var self = this,
    501                                 ids  = slice.call( arguments ),
    502575                                dfd  = $.Deferred();
    503576
    … …  
    556629
    557630        /**
    558          * Cast a string to a jQuery collection if it isn't already.
    559          *
    560          * @param {string|jQuery collection} element
     631         * Cast a string to a jQuery object if it isn't already.
     632         *
     633         * @param {string|JQuery} element A selector or an existing jQuery collection.
     634         * @return {JQuery} The jQuery collection.
    561635         */
    562636        api.ensure = function( element ) {
    … …  
    572646         * @alias wp.customize.Element
    573647         *
    574          * @constructor
     648         * @class
    575649         * @augments wp.customize.Value
    576650         * @augments wp.customize.Class
    … …  
    601675                        refresh = this.refresh;
    602676
    603                         this.update = function( to ) {
     677                        this.update = function( to, ...args ) {
    604678                                if ( to !== refresh.call( self ) ) {
    605                                         update.apply( this, arguments );
     679                                        update.call( this, to, ...args );
    606680                                }
    607681                        };
    … …  
    664738         * @alias wp.customize.Messenger
    665739         *
    666          * @constructor
     740         * @class
    667741         * @augments wp.customize.Class
    668742         * @mixes wp.customize.Events
    … …  
    672746                 * Create a new Value.
    673747                 *
    674                  * @param {string} key     Unique identifier.
    675                  * @param {mixed}  initial Initial value.
    676                  * @param {mixed}  options Options hash. Optional.
    677                  * @return {Value} Class instance of the Value.
     748                 * @param {string} key       Unique identifier.
     749                 * @param {*}      initial  Initial value.
     750                 * @param {*}      [options] Options hash.
     751                 * @return {wp.customize.Value} Class instance of the Value.
    678752                 */
    679753                add: function( key, initial, options ) {
    … …  
    684758                 * Initialize Messenger.
    685759                 *
    686                  * @param {Object} params  - Parameters to configure the messenger.
    687                  *        {string} params.url          - The URL to communicate with.
    688                  *        {window} params.targetWindow - The window instance to communicate with. Default window.parent.
    689                  *        {string} params.channel      - If provided, will send the channel with each message and only accept messages a matching channel.
    690                  * @param {Object} options - Extend any instance parameter or method with this object.
     760                 * @param {Object} params              Parameters to configure the messenger.
     761                 * @param {string} params.url          The URL to communicate with.
     762                 * @param {Window} params.targetWindow The window instance to communicate with. Default window.parent.
     763                 * @param {string} [params.channel]    If provided, will send the channel with each message and only accept messages a matching channel.
     764                 * @param {Object} [options]          Extend any instance parameter or method with this object.
    691765                 */
    692766                initialize: function( params, options ) {
    … …  
    708782                        this.add( 'targetWindow', null );
    709783                        // This avoids SecurityErrors when setting a window object in x-origin iframe'd scenarios.
    710                         this.targetWindow.set = function( to ) {
     784                        this.targetWindow.set = function( to, ...args ) {
    711785                                var from = this._value;
    712786
    713                                 to = this._setter.apply( this, arguments );
     787                                to = this._setter( to, ...args );
    714788                                to = this.validate( to );
    715789
    … …  
    749823                 * Receive data from the other window.
    750824                 *
    751                  * @param {jQuery.Event} event Event with embedded data.
     825                 * @param {JQuery.Event} event Event with embedded data.
    752826                 */
    753827                receive: function( event ) {
    … …  
    788862                 * Send data to the other window.
    789863                 *
    790                  * @param {string} id   The event name.
    791                  * @param {Object} data Data.
     864                 * @param {string} id     The event name.
     865                 * @param {*}      [data] Data.
    792866                 */
    793867                send: function( id, data ) {
    … …  
    822896         * @alias wp.customize.Notification
    823897         *
    824          * @param {string}  code - The error code.
    825          * @param {object}  params - Params.
    826          * @param {string}  params.message=null - The error message.
    827          * @param {string}  [params.type=error] - The notification type.
    828          * @param {boolean} [params.fromServer=false] - Whether the notification was server-sent.
    829          * @param {string}  [params.setting=null] - The setting ID that the notification is related to.
    830          * @param {*}       [params.data=null] - Any additional data.
     898         * @param {string}  code                     The error code.
     899         * @param {Object}  params                    Params.
     900         * @param {string}  [params.message=null]    The error message.
     901         * @param {string}  [params.type=error]       The notification type.
     902         * @param {boolean} [params.fromServer=false] Whether the notification was server-sent.
     903         * @param {string}  [params.setting=null]     The setting ID that the notification is related to.
     904         * @param {*}       [params.data=null]       Any additional data.
    831905         */
    832906        api.Notification = api.Class.extend(/** @lends wp.customize.Notification.prototype */{
    … …  
    838912                 *
    839913                 * @since 4.9.0
    840                  * @var {Function}
     914                 * @member {Function}
    841915                 */
    842916                template: null,
    … …  
    846920                 *
    847921                 * @since 4.9.0
    848                  * @var {string}
     922                 * @member {string}
    849923                 */
    850924                templateId: 'customize-notification',
    … …  
    854928                 *
    855929                 * @since 4.9.0
    856                  * @var {string}
     930                 * @member {string}
    857931                 */
    858932                containerClasses: '',
    … …  
    863937                 * @since 4.9.0
    864938                 *
    865                  * @param {string}   code - Notification code.
    866                  * @param {Object}   params - Notification parameters.
    867                  * @param {string}   params.message - Message.
    868                  * @param {string}   [params.type=error] - Type.
    869                  * @param {string}   [params.setting] - Related setting ID.
    870                  * @param {Function} [params.template] - Function for rendering template. If not provided, this will come from templateId.
    871                  * @param {string}   [params.templateId] - ID for template to render the notification.
    872                  * @param {string}   [params.containerClasses] - Additional class names to add to the notification container.
    873                  * @param {boolean}  [params.dismissible] - Whether the notification can be dismissed.
     939                 * @param {string}   code                     Notification code.
     940                 * @param {Object}   params                   Notification parameters.
     941                 * @param {string}   params.message           Message.
     942                 * @param {string}   [params.type=error]       Type.
     943                 * @param {string}   [params.setting]         Related setting ID.
     944                 * @param {Function} [params.template]         Function for rendering template. If not provided, this will come from templateId.
     945                 * @param {string}   [params.templateId]       ID for template to render the notification.
     946                 * @param {string}   [params.containerClasses] Additional class names to add to the notification container.
     947                 * @param {boolean}  [params.dismissible]     Whether the notification can be dismissed.
    874948                 */
    875949                initialize: function( code, params ) {
    … …  
    898972                 * @since 4.9.0
    899973                 *
    900                  * @return {jQuery} Notification container element.
     974                 * @return {JQuery} Notification container element.
    901975                 */
    902976                render: function() {
    … …  
    9361010         * @alias wp.customize.get
    9371011         *
    938          * @return {Object}
     1012         * @return {Object} All customize settings.
    9391013         */
    9401014        api.get = function() {
    … …  
    9911065         * @namespace wp.customize
    9921066         */
    993         exports.customize = api;
     1067        wp.customize = api;
    9941068})( wp, jQuery );
  • trunk/src/js/_enqueues/wp/customize/loader.js

    r57987 r63454  
    1313window.wp = window.wp || {};
    1414
    15 (function( exports, $ ){
     15/**
     16 * @param {Object}       wp The WordPress global object.
     17 * @param {JQueryStatic} $  The jQuery object.
     18 */
     19(function( wp, $ ){
    1620        var api = wp.customize,
    1721                Loader;
    … …  
    7781                },
    7882
     83                /**
     84                 * Handle popstate event.
     85                 *
     86                 * @param {JQuery.Event} e The popstate event.
     87                 * @return {void}
     88                 */
    7989                popstate: function( e ) {
    8090                        var state = e.originalEvent.state;
    … …  
    8696                },
    8797
     98                /**
     99                 * Handle hashchange event.
     100                 */
    88101                hashchange: function() {
    89102                        var hash = window.location.toString().split('#')[1];
    … …  
    98111                },
    99112
     113                /**
     114                 * Handle beforeunload event.
     115                 *
     116                 * @return {string|void} Confirmation message if there are unsaved changes.
     117                 */
    100118                beforeunload: function () {
    101119                        if ( ! Loader.saved() ) {
    … …  
    107125                 * Open the Customizer overlay for a specific URL.
    108126                 *
    109                  * @param string src URL to load in the Customizer.
     127                 * @param {string} src URL to load in the Customizer.
     128                 * @return {string|void} The URL, when navigating to it directly on mobile.
    110129                 */
    111130                open: function( src ) {
    … …  
    190209                },
    191210
     211                /**
     212                 * Push the state of the Customizer onto the history stack.
     213                 *
     214                 * @param {string} src URL to push.
     215                 */
    192216                pushState: function ( src ) {
    193217                        var hash = src.split( '?' )[1];
    … …  
    271295                 */
    272296                overlay: {
     297                        /**
     298                         * Show the overlay.
     299                         */
    273300                        show: function() {
    274301                                this.element.fadeIn( 200, Loader.opened );
    275302                        },
    276303
     304                        /**
     305                         * Hide the overlay.
     306                         */
    277307                        hide: function() {
    278308                                this.element.fadeOut( 200, Loader.closed );
  • trunk/tests/qunit/wp-admin/js/customize-base.js

    r47512 r63454  
    33jQuery( function( $ ) {
    44        var FooSuperClass, BarSubClass, foo, bar, ConstructorTestClass, newConstructor, constructorTest, $mockElement, mockString,
     5        ApplicatorTestClass, ArityTestClass,
    56        firstInitialValue, firstValueInstance, valuesInstance, wasCallbackFired, mockValueCallback;
    67
    … …  
    4849        });
    4950
    50         // @todo Test Class.applicator?
    51         // @todo Do we test object.instance?
     51        ApplicatorTestClass = wp.customize.Class.extend({
     52                initialize: function( firstArg, secondArg ) {
     53                        this.firstArg = firstArg;
     54                        this.secondArg = secondArg;
     55
     56                        // The instance is extended before initialize() runs.
     57                        this.hadExtraPropDuringInitialize = ( 'extraPropValue' === this.extraProp );
     58                }
     59        });
     60        QUnit.test( 'Class.applicator supplies the array as the initialize() arguments', function( assert ) {
     61                var applicatorTest = new ApplicatorTestClass(
     62                        wp.customize.Class.applicator,
     63                        [ 'firstArgValue', 'secondArgValue' ]
     64                );
     65                assert.equal( applicatorTest.firstArg, 'firstArgValue' );
     66                assert.equal( applicatorTest.secondArg, 'secondArgValue' );
     67        });
     68        QUnit.test( 'Class.applicator extends the instance before initialize() runs', function( assert ) {
     69                var applicatorTest = new ApplicatorTestClass(
     70                        wp.customize.Class.applicator,
     71                        [ 'firstArgValue' ],
     72                        { extraProp: 'extraPropValue' }
     73                );
     74                assert.equal( applicatorTest.firstArg, 'firstArgValue' );
     75                assert.equal( applicatorTest.extraProp, 'extraPropValue' );
     76                assert.ok( applicatorTest.hadExtraPropDuringInitialize );
     77        });
     78
     79        ArityTestClass = wp.customize.Class.extend({
     80                initialize: function( ...initializeArgs ) {
     81                        this.initializeArgCount = initializeArgs.length;
     82                }
     83        });
     84        QUnit.test( 'Class supplies initialize() with exactly the arguments it was given', function( assert ) {
     85                assert.equal( ( new ArityTestClass() ).initializeArgCount, 0 );
     86                assert.equal( ( new ArityTestClass( 'a' ) ).initializeArgCount, 1 );
     87                assert.equal( ( new ArityTestClass( 'a', 'b' ) ).initializeArgCount, 2 );
     88                assert.equal( ( new ArityTestClass( 'a', 'b', 'c' ) ).initializeArgCount, 3 );
     89                assert.equal( ( new ArityTestClass( 'a', 'b', 'c', 'd' ) ).initializeArgCount, 4 );
     90
     91                // The applicator form supplies the arguments as an array instead.
     92                assert.equal(
     93                        ( new ArityTestClass( wp.customize.Class.applicator, [ 'a', 'b' ] ) ).initializeArgCount,
     94                        2
     95                );
     96        });
     97
     98        QUnit.test( 'Class instance with an instance() method is callable as a function', function( assert ) {
     99                var instanceTest = new wp.customize.Value( 'initialValue' );
     100
     101                // Calling with no arguments delegates to get().
     102                assert.equal( instanceTest(), 'initialValue' );
     103
     104                // Calling with arguments delegates to set().
     105                instanceTest( 'updatedValue' );
     106                assert.equal( instanceTest.get(), 'updatedValue' );
     107                assert.equal( instanceTest(), 'updatedValue' );
     108        });
    52109
    53110        QUnit.module( 'Customize Base: Subclass' );
    … …  
    158215                firstValueInstance.set( 'newValue' );
    159216                assert.ok( wasCallbackFired );
     217        });
     218
     219        QUnit.test( '.bind() and .unbind() accept multiple callbacks', function( assert ) {
     220                var value = new wp.customize.Value( 'firstValue' ),
     221                        firstCallbackCount = 0,
     222                        secondCallbackCount = 0,
     223                        firstCallback = function() {
     224                                firstCallbackCount++;
     225                        },
     226                        secondCallback = function() {
     227                                secondCallbackCount++;
     228                        };
     229
     230                value.bind( firstCallback, secondCallback );
     231                value.set( 'secondValue' );
     232                assert.equal( firstCallbackCount, 1 );
     233                assert.equal( secondCallbackCount, 1 );
     234
     235                value.unbind( firstCallback, secondCallback );
     236                value.set( 'thirdValue' );
     237                assert.equal( firstCallbackCount, 1, 'First callback no longer fires once unbound.' );
     238                assert.equal( secondCallbackCount, 1, 'Second callback no longer fires once unbound.' );
     239        });
     240
     241        QUnit.test( '.link() follows multiple values, and .unlink() stops following them', function( assert ) {
     242                var follower = new wp.customize.Value( 'followerValue' ),
     243                        firstLeader = new wp.customize.Value( 'firstLeaderValue' ),
     244                        secondLeader = new wp.customize.Value( 'secondLeaderValue' );
     245
     246                follower.link( firstLeader, secondLeader );
     247
     248                firstLeader.set( 'firstLeaderUpdated' );
     249                assert.equal( follower.get(), 'firstLeaderUpdated' );
     250
     251                secondLeader.set( 'secondLeaderUpdated' );
     252                assert.equal( follower.get(), 'secondLeaderUpdated' );
     253
     254                // Linking is one-directional, so the leaders do not follow the follower.
     255                follower.set( 'followerUpdated' );
     256                assert.equal( firstLeader.get(), 'firstLeaderUpdated' );
     257                assert.equal( secondLeader.get(), 'secondLeaderUpdated' );
     258
     259                follower.unlink( firstLeader, secondLeader );
     260                firstLeader.set( 'firstLeaderUpdatedAgain' );
     261                secondLeader.set( 'secondLeaderUpdatedAgain' );
     262                assert.equal( follower.get(), 'followerUpdated', 'Value stops following once unlinked.' );
     263        });
     264
     265        QUnit.test( '.sync() keeps values updated in both directions, and .unsync() stops them', function( assert ) {
     266                var first = new wp.customize.Value( 'firstValue' ),
     267                        second = new wp.customize.Value( 'secondValue' );
     268
     269                first.sync( second );
     270
     271                second.set( 'setOnSecond' );
     272                assert.equal( first.get(), 'setOnSecond' );
     273
     274                first.set( 'setOnFirst' );
     275                assert.equal( second.get(), 'setOnFirst' );
     276
     277                first.unsync( second );
     278
     279                // Both directions have to stop, so check each of them.
     280                second.set( 'setOnSecondAgain' );
     281                assert.equal( first.get(), 'setOnFirst', 'First value stops following the second once unsynced.' );
     282                first.set( 'setOnFirstAgain' );
     283                assert.equal( second.get(), 'setOnSecondAgain', 'Second value stops following the first once unsynced.' );
    160284        });
    161285
    … …  
    206330        });
    207331
     332        QUnit.test( '.create() passes the extra arguments to the new value\'s initialize()', function( assert ) {
     333                var collection = new wp.customize.Values();
     334
     335                collection.create( 'createdValue', 'suppliedInitialValue', { extraProp: 'extraPropValue' } );
     336
     337                assert.ok( collection.has( 'createdValue' ) );
     338                assert.equal( collection( 'createdValue' ).get(), 'suppliedInitialValue' );
     339                assert.equal( collection( 'createdValue' ).extraProp, 'extraPropValue' );
     340        });
     341
     342        QUnit.test( '.when() invokes the callback once every requested value exists', function( assert ) {
     343                var collection = new wp.customize.Values(),
     344                        passedValues = null;
     345
     346                collection.add( 'existingValue', new wp.customize.Value( 'existingValueContents' ) );
     347
     348                collection.when( 'existingValue', 'pendingValue', function( existingValue, pendingValue ) {
     349                        passedValues = [ existingValue.get(), pendingValue.get() ];
     350                } );
     351
     352                assert.equal( passedValues, null, 'Callback waits for the value that does not exist yet.' );
     353
     354                collection.add( 'pendingValue', new wp.customize.Value( 'pendingValueContents' ) );
     355
     356                /*
     357                 * The promise returned by when() resolves by way of a timer, and this
     358                 * suite wraps every test with sinon's fake timers, so the clock has to
     359                 * be advanced before the callback runs.
     360                 */
     361                this.clock.tick( 10 );
     362
     363                assert.deepEqual(
     364                        passedValues,
     365                        [ 'existingValueContents', 'pendingValueContents' ],
     366                        'Callback is invoked with every requested value.'
     367                );
     368        });
     369
    208370        QUnit.module( 'Customize Base: Notification' );
    209371        QUnit.test( 'Notification object exists and has expected properties', function ( assert ) {
Note: See TracChangeset for help on using the changeset viewer.