1 window.wp = window.wp || {};
3 (function( exports, $ ){
4 var api, extend, ctor, inherits,
5 slice = Array.prototype.slice;
7 /* =====================================================================
8 * Micro-inheritance - thank you, backbone.js.
9 * ===================================================================== */
11 extend = function( protoProps, classProps ) {
12 var child = inherits( this, protoProps, classProps );
13 child.extend = this.extend;
17 // Shared empty constructor function to aid in prototype-chain creation.
20 // Helper function to correctly set up the prototype chain, for subclasses.
21 // Similar to `goog.inherits`, but uses a hash of prototype properties and
22 // class properties to be extended.
23 inherits = function( parent, protoProps, staticProps ) {
26 // The constructor function for the new subclass is either defined by you
27 // (the "constructor" property in your `extend` definition), or defaulted
28 // by us to simply call `super()`.
29 if ( protoProps && protoProps.hasOwnProperty( 'constructor' ) ) {
30 child = protoProps.constructor;
33 // Storing the result `super()` before returning the value
34 // prevents a bug in Opera where, if the constructor returns
35 // a function, Opera will reject the return value in favor of
36 // the original object. This causes all sorts of trouble.
37 var result = parent.apply( this, arguments );
42 // Inherit class (static) properties from parent.
43 $.extend( child, parent );
45 // Set the prototype chain to inherit from `parent`, without calling
46 // `parent`'s constructor function.
47 ctor.prototype = parent.prototype;
48 child.prototype = new ctor();
50 // Add prototype properties (instance properties) to the subclass,
53 $.extend( child.prototype, protoProps );
55 // Add static properties to the constructor function, if supplied.
57 $.extend( child, staticProps );
59 // Correctly set child's `prototype.constructor`.
60 child.prototype.constructor = child;
62 // Set a convenience property in case the parent's prototype is needed later.
63 child.__super__ = parent.prototype;
70 /* =====================================================================
72 * ===================================================================== */
74 api.Class = function( applicator, argsArray, options ) {
75 var magic, args = arguments;
77 if ( applicator && argsArray && api.Class.applicator === applicator ) {
79 $.extend( this, options || {} );
83 if ( this.instance ) {
85 return magic.instance.apply( magic, arguments );
88 $.extend( magic, this );
91 magic.initialize.apply( magic, args );
95 api.Class.applicator = {};
97 api.Class.prototype.initialize = function() {};
100 * Checks whether a given instance extended a constructor.
102 * The magic surrounding the instance parameter causes the instanceof
103 * keyword to return inaccurate results; it defaults to the function's
104 * prototype instead of the constructor chain. Hence this function.
106 api.Class.prototype.extended = function( constructor ) {
109 while ( typeof proto.constructor !== 'undefined' ) {
110 if ( proto.constructor === constructor )
112 if ( typeof proto.constructor.__super__ === 'undefined' )
114 proto = proto.constructor.__super__;
119 api.Class.extend = extend;
121 /* =====================================================================
123 * ===================================================================== */
126 trigger: function( id ) {
127 if ( this.topics && this.topics[ id ] )
128 this.topics[ id ].fireWith( this, slice.call( arguments, 1 ) );
132 bind: function( id ) {
133 this.topics = this.topics || {};
134 this.topics[ id ] = this.topics[ id ] || $.Callbacks();
135 this.topics[ id ].add.apply( this.topics[ id ], slice.call( arguments, 1 ) );
139 unbind: function( id ) {
140 if ( this.topics && this.topics[ id ] )
141 this.topics[ id ].remove.apply( this.topics[ id ], slice.call( arguments, 1 ) );
146 /* =====================================================================
147 * Observable values that support two-way binding.
148 * ===================================================================== */
150 api.Value = api.Class.extend({
151 initialize: function( initial, options ) {
152 this._value = initial; // @todo: potentially change this to a this.set() call.
153 this.callbacks = $.Callbacks();
155 $.extend( this, options || {} );
157 this.set = $.proxy( this.set, this );
161 * Magic. Returns a function that will become the instance.
162 * Set to null to prevent the instance from extending a function.
164 instance: function() {
165 return arguments.length ? this.set.apply( this, arguments ) : this.get();
172 set: function( to ) {
173 var from = this._value;
175 to = this._setter.apply( this, arguments );
176 to = this.validate( to );
178 // Bail if the sanitized value is null or unchanged.
179 if ( null === to || this._value === to )
184 this.callbacks.fireWith( this, [ to, from ] );
189 _setter: function( to ) {
193 setter: function( callback ) {
194 var from = this.get();
195 this._setter = callback;
196 // Temporarily clear value so setter can decide if it's valid.
202 resetSetter: function() {
203 this._setter = this.constructor.prototype._setter;
204 this.set( this.get() );
208 validate: function( value ) {
213 this.callbacks.add.apply( this.callbacks, arguments );
218 this.callbacks.remove.apply( this.callbacks, arguments );
222 link: function() { // values*
224 $.each( arguments, function() {
230 unlink: function() { // values*
232 $.each( arguments, function() {
238 sync: function() { // values*
240 $.each( arguments, function() {
247 unsync: function() { // values*
249 $.each( arguments, function() {
257 /* =====================================================================
258 * A collection of observable values.
259 * ===================================================================== */
261 api.Values = api.Class.extend({
262 defaultConstructor: api.Value,
264 initialize: function( options ) {
265 $.extend( this, options || {} );
268 this._deferreds = {};
271 instance: function( id ) {
272 if ( arguments.length === 1 )
273 return this.value( id );
275 return this.when.apply( this, arguments );
278 value: function( id ) {
279 return this._value[ id ];
282 has: function( id ) {
283 return typeof this._value[ id ] !== 'undefined';
286 add: function( id, value ) {
287 if ( this.has( id ) )
288 return this.value( id );
290 this._value[ id ] = value;
292 if ( value.extended( api.Value ) )
293 value.bind( this._change );
295 this.trigger( 'add', value );
297 if ( this._deferreds[ id ] )
298 this._deferreds[ id ].resolve();
300 return this._value[ id ];
303 create: function( id ) {
304 return this.add( id, new this.defaultConstructor( api.Class.applicator, slice.call( arguments, 1 ) ) );
307 each: function( callback, context ) {
308 context = typeof context === 'undefined' ? this : context;
310 $.each( this._value, function( key, obj ) {
311 callback.call( context, obj, key );
315 remove: function( id ) {
318 if ( this.has( id ) ) {
319 value = this.value( id );
320 this.trigger( 'remove', value );
321 if ( value.extended( api.Value ) )
322 value.unbind( this._change );
326 delete this._value[ id ];
327 delete this._deferreds[ id ];
331 * Runs a callback once all requested values exist.
333 * when( ids*, [callback] );
336 * when( id1, id2, id3, function( value1, value2, value3 ) {} );
338 * @returns $.Deferred.promise();
342 ids = slice.call( arguments ),
345 // If the last argument is a callback, bind it to .done()
346 if ( $.isFunction( ids[ ids.length - 1 ] ) )
347 dfd.done( ids.pop() );
349 $.when.apply( $, $.map( ids, function( id ) {
350 if ( self.has( id ) )
353 return self._deferreds[ id ] = self._deferreds[ id ] || $.Deferred();
354 })).done( function() {
355 var values = $.map( ids, function( id ) {
359 // If a value is missing, we've used at least one expired deferred.
360 // Call Values.when again to generate a new deferred.
361 if ( values.length !== ids.length ) {
362 // ids.push( callback );
363 self.when.apply( self, ids ).done( function() {
364 dfd.resolveWith( self, values );
369 dfd.resolveWith( self, values );
372 return dfd.promise();
375 _change: function() {
376 this.parent.trigger( 'change', this );
380 $.extend( api.Values.prototype, api.Events );
382 /* =====================================================================
383 * An observable value that syncs with an element.
385 * Handles inputs, selects, and textareas by default.
386 * ===================================================================== */
388 api.ensure = function( element ) {
389 return typeof element == 'string' ? $( element ) : element;
392 api.Element = api.Value.extend({
393 initialize: function( element, options ) {
395 synchronizer = api.Element.synchronizer.html,
396 type, update, refresh;
398 this.element = api.ensure( element );
401 if ( this.element.is('input, select, textarea') ) {
402 this.events += 'change';
403 synchronizer = api.Element.synchronizer.val;
405 if ( this.element.is('input') ) {
406 type = this.element.prop('type');
407 if ( api.Element.synchronizer[ type ] )
408 synchronizer = api.Element.synchronizer[ type ];
409 if ( 'text' === type || 'password' === type )
410 this.events += ' keyup';
411 } else if ( this.element.is('textarea') ) {
412 this.events += ' keyup';
416 api.Value.prototype.initialize.call( this, null, $.extend( options || {}, synchronizer ) );
417 this._value = this.get();
419 update = this.update;
420 refresh = this.refresh;
422 this.update = function( to ) {
423 if ( to !== refresh.call( self ) )
424 update.apply( this, arguments );
426 this.refresh = function() {
427 self.set( refresh.call( self ) );
430 this.bind( this.update );
431 this.element.bind( this.events, this.refresh );
434 find: function( selector ) {
435 return $( selector, this.element );
438 refresh: function() {},
440 update: function() {}
443 api.Element.synchronizer = {};
445 $.each( [ 'html', 'val' ], function( i, method ) {
446 api.Element.synchronizer[ method ] = {
447 update: function( to ) {
448 this.element[ method ]( to );
450 refresh: function() {
451 return this.element[ method ]();
456 api.Element.synchronizer.checkbox = {
457 update: function( to ) {
458 this.element.prop( 'checked', to );
460 refresh: function() {
461 return this.element.prop( 'checked' );
465 api.Element.synchronizer.radio = {
466 update: function( to ) {
467 this.element.filter( function() {
468 return this.value === to;
469 }).prop( 'checked', true );
471 refresh: function() {
472 return this.element.filter( ':checked' ).val();
476 /* =====================================================================
477 * Messenger for postMessage.
478 * ===================================================================== */
480 $.support.postMessage = !! window.postMessage;
482 api.Messenger = api.Class.extend({
483 add: function( key, initial, options ) {
484 return this[ key ] = new api.Value( initial, options );
488 * Initialize Messenger.
490 * @param {object} params Parameters to configure the messenger.
491 * {string} .url The URL to communicate with.
492 * {window} .targetWindow The window instance to communicate with. Default window.parent.
493 * {string} .channel If provided, will send the channel with each message and only accept messages a matching channel.
494 * @param {object} options Extend any instance parameter or method with this object.
496 initialize: function( params, options ) {
497 // Target the parent frame by default, but only if a parent frame exists.
498 var defaultTarget = window.parent == window ? null : window.parent;
500 $.extend( this, options || {} );
502 this.add( 'channel', params.channel );
503 this.add( 'url', params.url || '' );
504 this.add( 'targetWindow', params.targetWindow || defaultTarget );
505 this.add( 'origin', this.url() ).link( this.url ).setter( function( to ) {
506 return to.replace( /([^:]+:\/\/[^\/]+).*/, '$1' );
509 // Since we want jQuery to treat the receive function as unique
510 // to this instance, we give the function a new guid.
512 // This will prevent every Messenger's receive function from being
513 // unbound when calling $.off( 'message', this.receive );
514 this.receive = $.proxy( this.receive, this );
515 this.receive.guid = $.guid++;
517 $( window ).on( 'message', this.receive );
520 destroy: function() {
521 $( window ).off( 'message', this.receive );
524 receive: function( event ) {
527 event = event.originalEvent;
529 if ( ! this.targetWindow() )
532 // Check to make sure the origin is valid.
533 if ( this.origin() && event.origin !== this.origin() )
536 // Ensure we have a string that's JSON.parse-able
537 if ( typeof event.data !== 'string' || event.data[0] !== '{' ) {
541 message = JSON.parse( event.data );
543 // Check required message properties.
544 if ( ! message || ! message.id || typeof message.data === 'undefined' )
547 // Check if channel names match.
548 if ( ( message.channel || this.channel() ) && this.channel() !== message.channel )
551 this.trigger( message.id, message.data );
554 send: function( id, data ) {
557 data = typeof data === 'undefined' ? null : data;
559 if ( ! this.url() || ! this.targetWindow() )
562 message = { id: id, data: data };
563 if ( this.channel() )
564 message.channel = this.channel();
566 this.targetWindow().postMessage( JSON.stringify( message ), this.origin() );
570 // Add the Events mixin to api.Messenger.
571 $.extend( api.Messenger.prototype, api.Events );
573 /* =====================================================================
574 * Core customize object.
575 * ===================================================================== */
577 api = $.extend( new api.Values(), api );
578 api.get = function() {
581 this.each( function( obj, key ) {
582 result[ key ] = obj.get();
588 // Expose the API to the world.
589 exports.customize = api;