1 if ( typeof wp === 'undefined' )
4 (function( exports, $ ){
5 var api, extend, ctor, inherits,
6 slice = Array.prototype.slice;
8 /* =====================================================================
9 * Micro-inheritance - thank you, backbone.js.
10 * ===================================================================== */
12 extend = function( protoProps, classProps ) {
13 var child = inherits( this, protoProps, classProps );
14 child.extend = this.extend;
18 // Shared empty constructor function to aid in prototype-chain creation.
21 // Helper function to correctly set up the prototype chain, for subclasses.
22 // Similar to `goog.inherits`, but uses a hash of prototype properties and
23 // class properties to be extended.
24 inherits = function( parent, protoProps, staticProps ) {
27 // The constructor function for the new subclass is either defined by you
28 // (the "constructor" property in your `extend` definition), or defaulted
29 // by us to simply call `super()`.
30 if ( protoProps && protoProps.hasOwnProperty( 'constructor' ) ) {
31 child = protoProps.constructor;
34 // Storing the result `super()` before returning the value
35 // prevents a bug in Opera where, if the constructor returns
36 // a function, Opera will reject the return value in favor of
37 // the original object. This causes all sorts of trouble.
38 var result = parent.apply( this, arguments );
43 // Inherit class (static) properties from parent.
44 $.extend( child, parent );
46 // Set the prototype chain to inherit from `parent`, without calling
47 // `parent`'s constructor function.
48 ctor.prototype = parent.prototype;
49 child.prototype = new ctor();
51 // Add prototype properties (instance properties) to the subclass,
54 $.extend( child.prototype, protoProps );
56 // Add static properties to the constructor function, if supplied.
58 $.extend( child, staticProps );
60 // Correctly set child's `prototype.constructor`.
61 child.prototype.constructor = child;
63 // Set a convenience property in case the parent's prototype is needed later.
64 child.__super__ = parent.prototype;
71 /* =====================================================================
73 * ===================================================================== */
75 api.Class = function( applicator, argsArray, options ) {
76 var magic, args = arguments;
78 if ( applicator && argsArray && api.Class.applicator === applicator ) {
80 $.extend( this, options || {} );
84 if ( this.instance ) {
86 return magic.instance.apply( magic, arguments );
89 $.extend( magic, this );
92 magic.initialize.apply( magic, args );
96 api.Class.applicator = {};
98 api.Class.prototype.initialize = function() {};
101 * Checks whether a given instance extended a constructor.
103 * The magic surrounding the instance parameter causes the instanceof
104 * keyword to return inaccurate results; it defaults to the function's
105 * prototype instead of the constructor chain. Hence this function.
107 api.Class.prototype.extended = function( constructor ) {
110 while ( typeof proto.constructor !== 'undefined' ) {
111 if ( proto.constructor === constructor )
113 if ( typeof proto.constructor.__super__ === 'undefined' )
115 proto = proto.constructor.__super__;
120 api.Class.extend = extend;
122 /* =====================================================================
124 * ===================================================================== */
127 trigger: function( id ) {
128 if ( this.topics && this.topics[ id ] )
129 this.topics[ id ].fireWith( this, slice.call( arguments, 1 ) );
133 bind: function( id, callback ) {
134 this.topics = this.topics || {};
135 this.topics[ id ] = this.topics[ id ] || $.Callbacks();
136 this.topics[ id ].add.apply( this.topics[ id ], slice.call( arguments, 1 ) );
140 unbind: function( id, callback ) {
141 if ( this.topics && this.topics[ id ] )
142 this.topics[ id ].remove.apply( this.topics[ id ], slice.call( arguments, 1 ) );
147 /* =====================================================================
148 * Observable values that support two-way binding.
149 * ===================================================================== */
151 api.Value = api.Class.extend({
152 initialize: function( initial, options ) {
153 this._value = initial; // @todo: potentially change this to a this.set() call.
154 this.callbacks = $.Callbacks();
156 $.extend( this, options || {} );
158 this.set = $.proxy( this.set, this );
162 * Magic. Returns a function that will become the instance.
163 * Set to null to prevent the instance from extending a function.
165 instance: function() {
166 return arguments.length ? this.set.apply( this, arguments ) : this.get();
173 set: function( to ) {
174 var from = this._value;
176 to = this._setter.apply( this, arguments );
177 to = this.validate( to );
179 // Bail if the sanitized value is null or unchanged.
180 if ( null === to || this._value === to )
185 this.callbacks.fireWith( this, [ to, from ] );
190 _setter: function( to ) {
194 setter: function( callback ) {
195 var from = this.get();
196 this._setter = callback;
197 // Temporarily clear value so setter can decide if it's valid.
203 resetSetter: function() {
204 this._setter = this.constructor.prototype._setter;
205 this.set( this.get() );
209 validate: function( value ) {
213 bind: function( callback ) {
214 this.callbacks.add.apply( this.callbacks, arguments );
218 unbind: function( callback ) {
219 this.callbacks.remove.apply( this.callbacks, arguments );
223 link: function() { // values*
225 $.each( arguments, function() {
231 unlink: function() { // values*
233 $.each( arguments, function() {
239 sync: function() { // values*
241 $.each( arguments, function() {
248 unsync: function() { // values*
250 $.each( arguments, function() {
258 /* =====================================================================
259 * A collection of observable values.
260 * ===================================================================== */
262 api.Values = api.Class.extend({
263 defaultConstructor: api.Value,
265 initialize: function( options ) {
266 $.extend( this, options || {} );
269 this._deferreds = {};
272 instance: function( id ) {
273 if ( arguments.length === 1 )
274 return this.value( id );
276 return this.when.apply( this, arguments );
279 value: function( id ) {
280 return this._value[ id ];
283 has: function( id ) {
284 return typeof this._value[ id ] !== 'undefined';
287 add: function( id, value ) {
288 if ( this.has( id ) )
289 return this.value( id );
291 this._value[ id ] = value;
293 if ( value.extended( api.Value ) )
294 value.bind( this._change );
296 this.trigger( 'add', value );
298 if ( this._deferreds[ id ] )
299 this._deferreds[ id ].resolve();
301 return this._value[ id ];
304 create: function( id ) {
305 return this.add( id, new this.defaultConstructor( api.Class.applicator, slice.call( arguments, 1 ) ) );
308 each: function( callback, context ) {
309 context = typeof context === 'undefined' ? this : context;
311 $.each( this._value, function( key, obj ) {
312 callback.call( context, obj, key );
316 remove: function( id ) {
319 if ( this.has( id ) ) {
320 value = this.value( id );
321 this.trigger( 'remove', value );
322 if ( value.extended( api.Value ) )
323 value.unbind( this._change );
327 delete this._value[ id ];
328 delete this._deferreds[ id ];
332 * Runs a callback once all requested values exist.
334 * when( ids*, [callback] );
337 * when( id1, id2, id3, function( value1, value2, value3 ) {} );
339 * @returns $.Deferred.promise();
343 ids = slice.call( arguments ),
346 // If the last argument is a callback, bind it to .done()
347 if ( $.isFunction( ids[ ids.length - 1 ] ) )
348 dfd.done( ids.pop() );
350 $.when.apply( $, $.map( ids, function( id ) {
351 if ( self.has( id ) )
354 return self._deferreds[ id ] = self._deferreds[ id ] || $.Deferred();
355 })).done( function() {
356 var values = $.map( ids, function( id ) {
360 // If a value is missing, we've used at least one expired deferred.
361 // Call Values.when again to generate a new deferred.
362 if ( values.length !== ids.length ) {
363 // ids.push( callback );
364 self.when.apply( self, ids ).done( function() {
365 dfd.resolveWith( self, values );
370 dfd.resolveWith( self, values );
373 return dfd.promise();
376 _change: function() {
377 this.parent.trigger( 'change', this );
381 $.extend( api.Values.prototype, api.Events );
383 /* =====================================================================
384 * An observable value that syncs with an element.
386 * Handles inputs, selects, and textareas by default.
387 * ===================================================================== */
389 api.ensure = function( element ) {
390 return typeof element == 'string' ? $( element ) : element;
393 api.Element = api.Value.extend({
394 initialize: function( element, options ) {
396 synchronizer = api.Element.synchronizer.html,
397 type, update, refresh;
399 this.element = api.ensure( element );
402 if ( this.element.is('input, select, textarea') ) {
403 this.events += 'change';
404 synchronizer = api.Element.synchronizer.val;
406 if ( this.element.is('input') ) {
407 type = this.element.prop('type');
408 if ( api.Element.synchronizer[ type ] )
409 synchronizer = api.Element.synchronizer[ type ];
410 if ( 'text' === type || 'password' === type )
411 this.events += ' keyup';
412 } else if ( this.element.is('textarea') ) {
413 this.events += ' keyup';
417 api.Value.prototype.initialize.call( this, null, $.extend( options || {}, synchronizer ) );
418 this._value = this.get();
420 update = this.update;
421 refresh = this.refresh;
423 this.update = function( to ) {
424 if ( to !== refresh.call( self ) )
425 update.apply( this, arguments );
427 this.refresh = function() {
428 self.set( refresh.call( self ) );
431 this.bind( this.update );
432 this.element.bind( this.events, this.refresh );
435 find: function( selector ) {
436 return $( selector, this.element );
439 refresh: function() {},
441 update: function() {}
444 api.Element.synchronizer = {};
446 $.each( [ 'html', 'val' ], function( i, method ) {
447 api.Element.synchronizer[ method ] = {
448 update: function( to ) {
449 this.element[ method ]( to );
451 refresh: function() {
452 return this.element[ method ]();
457 api.Element.synchronizer.checkbox = {
458 update: function( to ) {
459 this.element.prop( 'checked', to );
461 refresh: function() {
462 return this.element.prop( 'checked' );
466 api.Element.synchronizer.radio = {
467 update: function( to ) {
468 this.element.filter( function() {
469 return this.value === to;
470 }).prop( 'checked', true );
472 refresh: function() {
473 return this.element.filter( ':checked' ).val();
477 /* =====================================================================
478 * Messenger for postMessage.
479 * ===================================================================== */
481 $.support.postMessage = !! window.postMessage;
483 api.Messenger = api.Class.extend({
484 add: function( key, initial, options ) {
485 return this[ key ] = new api.Value( initial, options );
489 * Initialize Messenger.
491 * @param {object} params Parameters to configure the messenger.
492 * {string} .url The URL to communicate with.
493 * {window} .targetWindow The window instance to communicate with. Default window.parent.
494 * {string} .channel If provided, will send the channel with each message and only accept messages a matching channel.
495 * @param {object} options Extend any instance parameter or method with this object.
497 initialize: function( params, options ) {
498 // Target the parent frame by default, but only if a parent frame exists.
499 var defaultTarget = window.parent == window ? null : window.parent;
501 $.extend( this, options || {} );
503 this.add( 'channel', params.channel );
504 this.add( 'url', params.url || '' );
505 this.add( 'targetWindow', params.targetWindow || defaultTarget );
506 this.add( 'origin', this.url() ).link( this.url ).setter( function( to ) {
507 return to.replace( /([^:]+:\/\/[^\/]+).*/, '$1' );
510 // Since we want jQuery to treat the receive function as unique
511 // to this instance, we give the function a new guid.
513 // This will prevent every Messenger's receive function from being
514 // unbound when calling $.off( 'message', this.receive );
515 this.receive = $.proxy( this.receive, this );
516 this.receive.guid = $.guid++;
518 $( window ).on( 'message', this.receive );
521 destroy: function() {
522 $( window ).off( 'message', this.receive );
525 receive: function( event ) {
528 event = event.originalEvent;
530 if ( ! this.targetWindow() )
533 // Check to make sure the origin is valid.
534 if ( this.origin() && event.origin !== this.origin() )
537 message = JSON.parse( event.data );
539 // Check required message properties.
540 if ( ! message || ! message.id || typeof message.data === 'undefined' )
543 // Check if channel names match.
544 if ( ( message.channel || this.channel() ) && this.channel() !== message.channel )
547 this.trigger( message.id, message.data );
550 send: function( id, data ) {
553 data = typeof data === 'undefined' ? null : data;
555 if ( ! this.url() || ! this.targetWindow() )
558 message = { id: id, data: data };
559 if ( this.channel() )
560 message.channel = this.channel();
562 this.targetWindow().postMessage( JSON.stringify( message ), this.origin() );
566 // Add the Events mixin to api.Messenger.
567 $.extend( api.Messenger.prototype, api.Events );
569 /* =====================================================================
570 * Core customize object.
571 * ===================================================================== */
573 api = $.extend( new api.Values(), api );
574 api.get = function() {
577 this.each( function( obj, key ) {
578 result[ key ] = obj.get();
584 // Expose the API to the world.
585 exports.customize = api;