1 window.wp = window.wp || {};
3 (function( exports, $ ){
4 var api = {}, ctor, inherits,
5 slice = Array.prototype.slice;
7 // Shared empty constructor function to aid in prototype-chain creation.
11 * Helper function to correctly set up the prototype chain, for subclasses.
12 * Similar to `goog.inherits`, but uses a hash of prototype properties and
13 * class properties to be extended.
15 * @param object parent Parent class constructor to inherit from.
16 * @param object protoProps Properties to apply to the prototype for use as class instance properties.
17 * @param object staticProps Properties to apply directly to the class constructor.
18 * @return child The subclassed constructor.
20 inherits = function( parent, protoProps, staticProps ) {
23 // The constructor function for the new subclass is either defined by you
24 // (the "constructor" property in your `extend` definition), or defaulted
25 // by us to simply call `super()`.
26 if ( protoProps && protoProps.hasOwnProperty( 'constructor' ) ) {
27 child = protoProps.constructor;
30 // Storing the result `super()` before returning the value
31 // prevents a bug in Opera where, if the constructor returns
32 // a function, Opera will reject the return value in favor of
33 // the original object. This causes all sorts of trouble.
34 var result = parent.apply( this, arguments );
39 // Inherit class (static) properties from parent.
40 $.extend( child, parent );
42 // Set the prototype chain to inherit from `parent`, without calling
43 // `parent`'s constructor function.
44 ctor.prototype = parent.prototype;
45 child.prototype = new ctor();
47 // Add prototype properties (instance properties) to the subclass,
50 $.extend( child.prototype, protoProps );
52 // Add static properties to the constructor function, if supplied.
54 $.extend( child, staticProps );
56 // Correctly set child's `prototype.constructor`.
57 child.prototype.constructor = child;
59 // Set a convenience property in case the parent's prototype is needed later.
60 child.__super__ = parent.prototype;
66 * Base class for object inheritance.
68 api.Class = function( applicator, argsArray, options ) {
69 var magic, args = arguments;
71 if ( applicator && argsArray && api.Class.applicator === applicator ) {
73 $.extend( this, options || {} );
77 if ( this.instance ) {
79 return magic.instance.apply( magic, arguments );
82 $.extend( magic, this );
85 magic.initialize.apply( magic, args );
90 * Creates a subclass of the class.
92 * @param object protoProps Properties to apply to the prototype.
93 * @param object staticProps Properties to apply directly to the class.
94 * @return child The subclass.
96 api.Class.extend = function( protoProps, classProps ) {
97 var child = inherits( this, protoProps, classProps );
98 child.extend = this.extend;
102 api.Class.applicator = {};
104 api.Class.prototype.initialize = function() {};
107 * Checks whether a given instance extended a constructor.
109 * The magic surrounding the instance parameter causes the instanceof
110 * keyword to return inaccurate results; it defaults to the function's
111 * prototype instead of the constructor chain. Hence this function.
113 api.Class.prototype.extended = function( constructor ) {
116 while ( typeof proto.constructor !== 'undefined' ) {
117 if ( proto.constructor === constructor )
119 if ( typeof proto.constructor.__super__ === 'undefined' )
121 proto = proto.constructor.__super__;
127 * An events manager object, offering the ability to bind to and trigger events.
132 trigger: function( id ) {
133 if ( this.topics && this.topics[ id ] )
134 this.topics[ id ].fireWith( this, slice.call( arguments, 1 ) );
138 bind: function( id ) {
139 this.topics = this.topics || {};
140 this.topics[ id ] = this.topics[ id ] || $.Callbacks();
141 this.topics[ id ].add.apply( this.topics[ id ], slice.call( arguments, 1 ) );
145 unbind: function( id ) {
146 if ( this.topics && this.topics[ id ] )
147 this.topics[ id ].remove.apply( this.topics[ id ], slice.call( arguments, 1 ) );
153 * Observable values that support two-way binding.
157 api.Value = api.Class.extend({
158 initialize: function( initial, options ) {
159 this._value = initial; // @todo: potentially change this to a this.set() call.
160 this.callbacks = $.Callbacks();
163 $.extend( this, options || {} );
165 this.set = $.proxy( this.set, this );
169 * Magic. Returns a function that will become the instance.
170 * Set to null to prevent the instance from extending a function.
172 instance: function() {
173 return arguments.length ? this.set.apply( this, arguments ) : this.get();
180 set: function( to ) {
181 var from = this._value;
183 to = this._setter.apply( this, arguments );
184 to = this.validate( to );
186 // Bail if the sanitized value is null or unchanged.
187 if ( null === to || _.isEqual( from, to ) ) {
194 this.callbacks.fireWith( this, [ to, from ] );
199 _setter: function( to ) {
203 setter: function( callback ) {
204 var from = this.get();
205 this._setter = callback;
206 // Temporarily clear value so setter can decide if it's valid.
212 resetSetter: function() {
213 this._setter = this.constructor.prototype._setter;
214 this.set( this.get() );
218 validate: function( value ) {
223 this.callbacks.add.apply( this.callbacks, arguments );
228 this.callbacks.remove.apply( this.callbacks, arguments );
232 link: function() { // values*
234 $.each( arguments, function() {
240 unlink: function() { // values*
242 $.each( arguments, function() {
248 sync: function() { // values*
250 $.each( arguments, function() {
257 unsync: function() { // values*
259 $.each( arguments, function() {
268 * A collection of observable values.
271 * @augments wp.customize.Class
272 * @mixes wp.customize.Events
274 api.Values = api.Class.extend({
275 defaultConstructor: api.Value,
277 initialize: function( options ) {
278 $.extend( this, options || {} );
281 this._deferreds = {};
284 instance: function( id ) {
285 if ( arguments.length === 1 )
286 return this.value( id );
288 return this.when.apply( this, arguments );
291 value: function( id ) {
292 return this._value[ id ];
295 has: function( id ) {
296 return typeof this._value[ id ] !== 'undefined';
299 add: function( id, value ) {
300 if ( this.has( id ) )
301 return this.value( id );
303 this._value[ id ] = value;
305 if ( value.extended( api.Value ) )
306 value.bind( this._change );
308 this.trigger( 'add', value );
310 if ( this._deferreds[ id ] )
311 this._deferreds[ id ].resolve();
313 return this._value[ id ];
316 create: function( id ) {
317 return this.add( id, new this.defaultConstructor( api.Class.applicator, slice.call( arguments, 1 ) ) );
320 each: function( callback, context ) {
321 context = typeof context === 'undefined' ? this : context;
323 $.each( this._value, function( key, obj ) {
324 callback.call( context, obj, key );
328 remove: function( id ) {
331 if ( this.has( id ) ) {
332 value = this.value( id );
333 this.trigger( 'remove', value );
334 if ( value.extended( api.Value ) )
335 value.unbind( this._change );
339 delete this._value[ id ];
340 delete this._deferreds[ id ];
344 * Runs a callback once all requested values exist.
346 * when( ids*, [callback] );
349 * when( id1, id2, id3, function( value1, value2, value3 ) {} );
351 * @returns $.Deferred.promise();
355 ids = slice.call( arguments ),
358 // If the last argument is a callback, bind it to .done()
359 if ( $.isFunction( ids[ ids.length - 1 ] ) )
360 dfd.done( ids.pop() );
362 $.when.apply( $, $.map( ids, function( id ) {
363 if ( self.has( id ) )
366 return self._deferreds[ id ] = self._deferreds[ id ] || $.Deferred();
367 })).done( function() {
368 var values = $.map( ids, function( id ) {
372 // If a value is missing, we've used at least one expired deferred.
373 // Call Values.when again to generate a new deferred.
374 if ( values.length !== ids.length ) {
375 // ids.push( callback );
376 self.when.apply( self, ids ).done( function() {
377 dfd.resolveWith( self, values );
382 dfd.resolveWith( self, values );
385 return dfd.promise();
388 _change: function() {
389 this.parent.trigger( 'change', this );
393 $.extend( api.Values.prototype, api.Events );
397 * Cast a string to a jQuery collection if it isn't already.
399 * @param {string|jQuery collection} element
401 api.ensure = function( element ) {
402 return typeof element == 'string' ? $( element ) : element;
406 * An observable value that syncs with an element.
408 * Handles inputs, selects, and textareas by default.
411 * @augments wp.customize.Value
412 * @augments wp.customize.Class
414 api.Element = api.Value.extend({
415 initialize: function( element, options ) {
417 synchronizer = api.Element.synchronizer.html,
418 type, update, refresh;
420 this.element = api.ensure( element );
423 if ( this.element.is('input, select, textarea') ) {
424 this.events += 'change';
425 synchronizer = api.Element.synchronizer.val;
427 if ( this.element.is('input') ) {
428 type = this.element.prop('type');
429 if ( api.Element.synchronizer[ type ] ) {
430 synchronizer = api.Element.synchronizer[ type ];
432 if ( 'text' === type || 'password' === type ) {
433 this.events += ' keyup';
434 } else if ( 'range' === type ) {
435 this.events += ' input propertychange';
437 } else if ( this.element.is('textarea') ) {
438 this.events += ' keyup';
442 api.Value.prototype.initialize.call( this, null, $.extend( options || {}, synchronizer ) );
443 this._value = this.get();
445 update = this.update;
446 refresh = this.refresh;
448 this.update = function( to ) {
449 if ( to !== refresh.call( self ) )
450 update.apply( this, arguments );
452 this.refresh = function() {
453 self.set( refresh.call( self ) );
456 this.bind( this.update );
457 this.element.bind( this.events, this.refresh );
460 find: function( selector ) {
461 return $( selector, this.element );
464 refresh: function() {},
466 update: function() {}
469 api.Element.synchronizer = {};
471 $.each( [ 'html', 'val' ], function( index, method ) {
472 api.Element.synchronizer[ method ] = {
473 update: function( to ) {
474 this.element[ method ]( to );
476 refresh: function() {
477 return this.element[ method ]();
482 api.Element.synchronizer.checkbox = {
483 update: function( to ) {
484 this.element.prop( 'checked', to );
486 refresh: function() {
487 return this.element.prop( 'checked' );
491 api.Element.synchronizer.radio = {
492 update: function( to ) {
493 this.element.filter( function() {
494 return this.value === to;
495 }).prop( 'checked', true );
497 refresh: function() {
498 return this.element.filter( ':checked' ).val();
502 $.support.postMessage = !! window.postMessage;
505 * Messenger for postMessage.
508 * @augments wp.customize.Class
509 * @mixes wp.customize.Events
511 api.Messenger = api.Class.extend({
513 * Create a new Value.
515 * @param {string} key Unique identifier.
516 * @param {mixed} initial Initial value.
517 * @param {mixed} options Options hash. Optional.
518 * @return {Value} Class instance of the Value.
520 add: function( key, initial, options ) {
521 return this[ key ] = new api.Value( initial, options );
525 * Initialize Messenger.
527 * @param {object} params Parameters to configure the messenger.
528 * {string} .url The URL to communicate with.
529 * {window} .targetWindow The window instance to communicate with. Default window.parent.
530 * {string} .channel If provided, will send the channel with each message and only accept messages a matching channel.
531 * @param {object} options Extend any instance parameter or method with this object.
533 initialize: function( params, options ) {
534 // Target the parent frame by default, but only if a parent frame exists.
535 var defaultTarget = window.parent == window ? null : window.parent;
537 $.extend( this, options || {} );
539 this.add( 'channel', params.channel );
540 this.add( 'url', params.url || '' );
541 this.add( 'origin', this.url() ).link( this.url ).setter( function( to ) {
542 return to.replace( /([^:]+:\/\/[^\/]+).*/, '$1' );
545 // first add with no value
546 this.add( 'targetWindow', null );
547 // This avoids SecurityErrors when setting a window object in x-origin iframe'd scenarios.
548 this.targetWindow.set = function( to ) {
549 var from = this._value;
551 to = this._setter.apply( this, arguments );
552 to = this.validate( to );
554 if ( null === to || from === to ) {
561 this.callbacks.fireWith( this, [ to, from ] );
566 this.targetWindow( params.targetWindow || defaultTarget );
569 // Since we want jQuery to treat the receive function as unique
570 // to this instance, we give the function a new guid.
572 // This will prevent every Messenger's receive function from being
573 // unbound when calling $.off( 'message', this.receive );
574 this.receive = $.proxy( this.receive, this );
575 this.receive.guid = $.guid++;
577 $( window ).on( 'message', this.receive );
580 destroy: function() {
581 $( window ).off( 'message', this.receive );
584 receive: function( event ) {
587 event = event.originalEvent;
589 if ( ! this.targetWindow() )
592 // Check to make sure the origin is valid.
593 if ( this.origin() && event.origin !== this.origin() )
596 // Ensure we have a string that's JSON.parse-able
597 if ( typeof event.data !== 'string' || event.data[0] !== '{' ) {
601 message = JSON.parse( event.data );
603 // Check required message properties.
604 if ( ! message || ! message.id || typeof message.data === 'undefined' )
607 // Check if channel names match.
608 if ( ( message.channel || this.channel() ) && this.channel() !== message.channel )
611 this.trigger( message.id, message.data );
614 send: function( id, data ) {
617 data = typeof data === 'undefined' ? null : data;
619 if ( ! this.url() || ! this.targetWindow() )
622 message = { id: id, data: data };
623 if ( this.channel() )
624 message.channel = this.channel();
626 this.targetWindow().postMessage( JSON.stringify( message ), this.origin() );
630 // Add the Events mixin to api.Messenger.
631 $.extend( api.Messenger.prototype, api.Events );
633 // Core customize object.
634 api = $.extend( new api.Values(), api );
635 api.get = function() {
638 this.each( function( obj, key ) {
639 result[ key ] = obj.get();
645 // Expose the API publicly on window.wp.customize
646 exports.customize = api;