[ Index ] |
PHP Cross Reference of MediaWiki-1.24.0 |
[Summary view] [Print] [Text view]
1 /*! 2 * OOjs v1.1.1 optimised for jQuery 3 * https://www.mediawiki.org/wiki/OOjs 4 * 5 * Copyright 2011-2014 OOjs Team and other contributors. 6 * Released under the MIT license 7 * http://oojs.mit-license.org 8 * 9 * Date: 2014-09-11T00:40:09Z 10 */ 11 ( function ( global ) { 12 13 'use strict'; 14 15 /*exported toString */ 16 var 17 /** 18 * Namespace for all classes, static methods and static properties. 19 * @class OO 20 * @singleton 21 */ 22 oo = {}, 23 hasOwn = oo.hasOwnProperty, 24 toString = oo.toString; 25 26 /* Class Methods */ 27 28 /** 29 * Utility to initialize a class for OO inheritance. 30 * 31 * Currently this just initializes an empty static object. 32 * 33 * @param {Function} fn 34 */ 35 oo.initClass = function ( fn ) { 36 fn.static = fn.static || {}; 37 }; 38 39 /** 40 * Inherit from prototype to another using Object#create. 41 * 42 * Beware: This redefines the prototype, call before setting your prototypes. 43 * 44 * Beware: This redefines the prototype, can only be called once on a function. 45 * If called multiple times on the same function, the previous prototype is lost. 46 * This is how prototypal inheritance works, it can only be one straight chain 47 * (just like classical inheritance in PHP for example). If you need to work with 48 * multiple constructors consider storing an instance of the other constructor in a 49 * property instead, or perhaps use a mixin (see OO.mixinClass). 50 * 51 * function Thing() {} 52 * Thing.prototype.exists = function () {}; 53 * 54 * function Person() { 55 * Person.super.apply( this, arguments ); 56 * } 57 * OO.inheritClass( Person, Thing ); 58 * Person.static.defaultEyeCount = 2; 59 * Person.prototype.walk = function () {}; 60 * 61 * function Jumper() { 62 * Jumper.super.apply( this, arguments ); 63 * } 64 * OO.inheritClass( Jumper, Person ); 65 * Jumper.prototype.jump = function () {}; 66 * 67 * Jumper.static.defaultEyeCount === 2; 68 * var x = new Jumper(); 69 * x.jump(); 70 * x.walk(); 71 * x instanceof Thing && x instanceof Person && x instanceof Jumper; 72 * 73 * @param {Function} targetFn 74 * @param {Function} originFn 75 * @throws {Error} If target already inherits from origin 76 */ 77 oo.inheritClass = function ( targetFn, originFn ) { 78 if ( targetFn.prototype instanceof originFn ) { 79 throw new Error( 'Target already inherits from origin' ); 80 } 81 82 var targetConstructor = targetFn.prototype.constructor; 83 84 // Using ['super'] instead of .super because 'super' is not supported 85 // by IE 8 and below (bug 63303). 86 // Provide .parent as alias for code supporting older browsers which 87 // allows people to comply with their style guide. 88 targetFn['super'] = targetFn.parent = originFn; 89 90 targetFn.prototype = Object.create( originFn.prototype, { 91 // Restore constructor property of targetFn 92 constructor: { 93 value: targetConstructor, 94 enumerable: false, 95 writable: true, 96 configurable: true 97 } 98 } ); 99 100 // Extend static properties - always initialize both sides 101 oo.initClass( originFn ); 102 targetFn.static = Object.create( originFn.static ); 103 }; 104 105 /** 106 * Copy over *own* prototype properties of a mixin. 107 * 108 * The 'constructor' (whether implicit or explicit) is not copied over. 109 * 110 * This does not create inheritance to the origin. If inheritance is needed 111 * use oo.inheritClass instead. 112 * 113 * Beware: This can redefine a prototype property, call before setting your prototypes. 114 * 115 * Beware: Don't call before oo.inheritClass. 116 * 117 * function Foo() {} 118 * function Context() {} 119 * 120 * // Avoid repeating this code 121 * function ContextLazyLoad() {} 122 * ContextLazyLoad.prototype.getContext = function () { 123 * if ( !this.context ) { 124 * this.context = new Context(); 125 * } 126 * return this.context; 127 * }; 128 * 129 * function FooBar() {} 130 * OO.inheritClass( FooBar, Foo ); 131 * OO.mixinClass( FooBar, ContextLazyLoad ); 132 * 133 * @param {Function} targetFn 134 * @param {Function} originFn 135 */ 136 oo.mixinClass = function ( targetFn, originFn ) { 137 var key; 138 139 // Copy prototype properties 140 for ( key in originFn.prototype ) { 141 if ( key !== 'constructor' && hasOwn.call( originFn.prototype, key ) ) { 142 targetFn.prototype[key] = originFn.prototype[key]; 143 } 144 } 145 146 // Copy static properties - always initialize both sides 147 oo.initClass( targetFn ); 148 if ( originFn.static ) { 149 for ( key in originFn.static ) { 150 if ( hasOwn.call( originFn.static, key ) ) { 151 targetFn.static[key] = originFn.static[key]; 152 } 153 } 154 } else { 155 oo.initClass( originFn ); 156 } 157 }; 158 159 /* Object Methods */ 160 161 /** 162 * Create a new object that is an instance of the same 163 * constructor as the input, inherits from the same object 164 * and contains the same own properties. 165 * 166 * This makes a shallow non-recursive copy of own properties. 167 * To create a recursive copy of plain objects, use #copy. 168 * 169 * var foo = new Person( mom, dad ); 170 * foo.setAge( 21 ); 171 * var foo2 = OO.cloneObject( foo ); 172 * foo.setAge( 22 ); 173 * 174 * // Then 175 * foo2 !== foo; // true 176 * foo2 instanceof Person; // true 177 * foo2.getAge(); // 21 178 * foo.getAge(); // 22 179 * 180 * @param {Object} origin 181 * @return {Object} Clone of origin 182 */ 183 oo.cloneObject = function ( origin ) { 184 var key, r; 185 186 r = Object.create( origin.constructor.prototype ); 187 188 for ( key in origin ) { 189 if ( hasOwn.call( origin, key ) ) { 190 r[key] = origin[key]; 191 } 192 } 193 194 return r; 195 }; 196 197 /** 198 * Get an array of all property values in an object. 199 * 200 * @param {Object} Object to get values from 201 * @return {Array} List of object values 202 */ 203 oo.getObjectValues = function ( obj ) { 204 var key, values; 205 206 if ( obj !== Object( obj ) ) { 207 throw new TypeError( 'Called on non-object' ); 208 } 209 210 values = []; 211 for ( key in obj ) { 212 if ( hasOwn.call( obj, key ) ) { 213 values[values.length] = obj[key]; 214 } 215 } 216 217 return values; 218 }; 219 220 /** 221 * Recursively compare properties between two objects. 222 * 223 * A false result may be caused by property inequality or by properties in one object missing from 224 * the other. An asymmetrical test may also be performed, which checks only that properties in the 225 * first object are present in the second object, but not the inverse. 226 * 227 * If either a or b is null or undefined it will be treated as an empty object. 228 * 229 * @param {Object|undefined|null} a First object to compare 230 * @param {Object|undefined|null} b Second object to compare 231 * @param {boolean} [asymmetrical] Whether to check only that b contains values from a 232 * @return {boolean} If the objects contain the same values as each other 233 */ 234 oo.compare = function ( a, b, asymmetrical ) { 235 var aValue, bValue, aType, bType, k; 236 237 if ( a === b ) { 238 return true; 239 } 240 241 a = a || {}; 242 b = b || {}; 243 244 for ( k in a ) { 245 if ( !hasOwn.call( a, k ) ) { 246 // Support es3-shim: Without this filter, comparing [] to {} will be false in ES3 247 // because the shimmed "forEach" is enumerable and shows up in Array but not Object. 248 continue; 249 } 250 251 aValue = a[k]; 252 bValue = b[k]; 253 aType = typeof aValue; 254 bType = typeof bValue; 255 if ( aType !== bType || 256 ( 257 ( aType === 'string' || aType === 'number' || aType === 'boolean' ) && 258 aValue !== bValue 259 ) || 260 ( aValue === Object( aValue ) && !oo.compare( aValue, bValue, asymmetrical ) ) ) { 261 return false; 262 } 263 } 264 // If the check is not asymmetrical, recursing with the arguments swapped will verify our result 265 return asymmetrical ? true : oo.compare( b, a, true ); 266 }; 267 268 /** 269 * Create a plain deep copy of any kind of object. 270 * 271 * Copies are deep, and will either be an object or an array depending on `source`. 272 * 273 * @param {Object} source Object to copy 274 * @param {Function} [leafCallback] Applied to leaf values after they are cloned but before they are added to the clone 275 * @param {Function} [nodeCallback] Applied to all values before they are cloned. If the nodeCallback returns a value other than undefined, the returned value is used instead of attempting to clone. 276 * @return {Object} Copy of source object 277 */ 278 oo.copy = function ( source, leafCallback, nodeCallback ) { 279 var key, destination; 280 281 if ( nodeCallback ) { 282 // Extensibility: check before attempting to clone source. 283 destination = nodeCallback( source ); 284 if ( destination !== undefined ) { 285 return destination; 286 } 287 } 288 289 if ( Array.isArray( source ) ) { 290 // Array (fall through) 291 destination = new Array( source.length ); 292 } else if ( source && typeof source.clone === 'function' ) { 293 // Duck type object with custom clone method 294 return leafCallback ? leafCallback( source.clone() ) : source.clone(); 295 } else if ( source && typeof source.cloneNode === 'function' ) { 296 // DOM Node 297 return leafCallback ? 298 leafCallback( source.cloneNode( true ) ) : 299 source.cloneNode( true ); 300 } else if ( oo.isPlainObject( source ) ) { 301 // Plain objects (fall through) 302 destination = {}; 303 } else { 304 // Non-plain objects (incl. functions) and primitive values 305 return leafCallback ? leafCallback( source ) : source; 306 } 307 308 // source is an array or a plain object 309 for ( key in source ) { 310 destination[key] = oo.copy( source[key], leafCallback, nodeCallback ); 311 } 312 313 // This is an internal node, so we don't apply the leafCallback. 314 return destination; 315 }; 316 317 /** 318 * Generate a hash of an object based on its name and data. 319 * 320 * Performance optimization: <http://jsperf.com/ve-gethash-201208#/toJson_fnReplacerIfAoForElse> 321 * 322 * To avoid two objects with the same values generating different hashes, we utilize the replacer 323 * argument of JSON.stringify and sort the object by key as it's being serialized. This may or may 324 * not be the fastest way to do this; we should investigate this further. 325 * 326 * Objects and arrays are hashed recursively. When hashing an object that has a .getHash() 327 * function, we call that function and use its return value rather than hashing the object 328 * ourselves. This allows classes to define custom hashing. 329 * 330 * @param {Object} val Object to generate hash for 331 * @return {string} Hash of object 332 */ 333 oo.getHash = function ( val ) { 334 return JSON.stringify( val, oo.getHash.keySortReplacer ); 335 }; 336 337 /** 338 * Sort objects by key (helper function for OO.getHash). 339 * 340 * This is a callback passed into JSON.stringify. 341 * 342 * @method getHash_keySortReplacer 343 * @param {string} key Property name of value being replaced 344 * @param {Mixed} val Property value to replace 345 * @return {Mixed} Replacement value 346 */ 347 oo.getHash.keySortReplacer = function ( key, val ) { 348 var normalized, keys, i, len; 349 if ( val && typeof val.getHashObject === 'function' ) { 350 // This object has its own custom hash function, use it 351 val = val.getHashObject(); 352 } 353 if ( !Array.isArray( val ) && Object( val ) === val ) { 354 // Only normalize objects when the key-order is ambiguous 355 // (e.g. any object not an array). 356 normalized = {}; 357 keys = Object.keys( val ).sort(); 358 i = 0; 359 len = keys.length; 360 for ( ; i < len; i += 1 ) { 361 normalized[keys[i]] = val[keys[i]]; 362 } 363 return normalized; 364 365 // Primitive values and arrays get stable hashes 366 // by default. Lets those be stringified as-is. 367 } else { 368 return val; 369 } 370 }; 371 372 /** 373 * Compute the union (duplicate-free merge) of a set of arrays. 374 * 375 * Arrays values must be convertable to object keys (strings). 376 * 377 * By building an object (with the values for keys) in parallel with 378 * the array, a new item's existence in the union can be computed faster. 379 * 380 * @param {Array...} arrays Arrays to union 381 * @return {Array} Union of the arrays 382 */ 383 oo.simpleArrayUnion = function () { 384 var i, ilen, arr, j, jlen, 385 obj = {}, 386 result = []; 387 388 for ( i = 0, ilen = arguments.length; i < ilen; i++ ) { 389 arr = arguments[i]; 390 for ( j = 0, jlen = arr.length; j < jlen; j++ ) { 391 if ( !obj[ arr[j] ] ) { 392 obj[ arr[j] ] = true; 393 result.push( arr[j] ); 394 } 395 } 396 } 397 398 return result; 399 }; 400 401 /** 402 * Combine arrays (intersection or difference). 403 * 404 * An intersection checks the item exists in 'b' while difference checks it doesn't. 405 * 406 * Arrays values must be convertable to object keys (strings). 407 * 408 * By building an object (with the values for keys) of 'b' we can 409 * compute the result faster. 410 * 411 * @private 412 * @param {Array} a First array 413 * @param {Array} b Second array 414 * @param {boolean} includeB Whether to items in 'b' 415 * @return {Array} Combination (intersection or difference) of arrays 416 */ 417 function simpleArrayCombine( a, b, includeB ) { 418 var i, ilen, isInB, 419 bObj = {}, 420 result = []; 421 422 for ( i = 0, ilen = b.length; i < ilen; i++ ) { 423 bObj[ b[i] ] = true; 424 } 425 426 for ( i = 0, ilen = a.length; i < ilen; i++ ) { 427 isInB = !!bObj[ a[i] ]; 428 if ( isInB === includeB ) { 429 result.push( a[i] ); 430 } 431 } 432 433 return result; 434 } 435 436 /** 437 * Compute the intersection of two arrays (items in both arrays). 438 * 439 * Arrays values must be convertable to object keys (strings). 440 * 441 * @param {Array} a First array 442 * @param {Array} b Second array 443 * @return {Array} Intersection of arrays 444 */ 445 oo.simpleArrayIntersection = function ( a, b ) { 446 return simpleArrayCombine( a, b, true ); 447 }; 448 449 /** 450 * Compute the difference of two arrays (items in 'a' but not 'b'). 451 * 452 * Arrays values must be convertable to object keys (strings). 453 * 454 * @param {Array} a First array 455 * @param {Array} b Second array 456 * @return {Array} Intersection of arrays 457 */ 458 oo.simpleArrayDifference = function ( a, b ) { 459 return simpleArrayCombine( a, b, false ); 460 }; 461 462 /*global $ */ 463 464 oo.isPlainObject = $.isPlainObject; 465 466 /*global hasOwn */ 467 468 ( function () { 469 470 /** 471 * @class OO.EventEmitter 472 * 473 * @constructor 474 */ 475 oo.EventEmitter = function OoEventEmitter() { 476 // Properties 477 478 /** 479 * Storage of bound event handlers by event name. 480 * 481 * @property 482 */ 483 this.bindings = {}; 484 }; 485 486 oo.initClass( oo.EventEmitter ); 487 488 /* Private helper functions */ 489 490 /** 491 * Validate a function or method call in a context 492 * 493 * For a method name, check that it names a function in the context object 494 * 495 * @private 496 * @param {Function|string} method Function or method name 497 * @param {Mixed} context The context of the call 498 * @throws {Error} A method name is given but there is no context 499 * @throws {Error} In the context object, no property exists with the given name 500 * @throws {Error} In the context object, the named property is not a function 501 */ 502 function validateMethod( method, context ) { 503 // Validate method and context 504 if ( typeof method === 'string' ) { 505 // Validate method 506 if ( context === undefined || context === null ) { 507 throw new Error( 'Method name "' + method + '" has no context.' ); 508 } 509 if ( !( method in context ) ) { 510 // Technically the method does not need to exist yet: it could be 511 // added before call time. But this probably signals a typo. 512 throw new Error( 'Method not found: "' + method + '"' ); 513 } 514 if ( typeof context[method] !== 'function' ) { 515 // Technically the property could be replaced by a function before 516 // call time. But this probably signals a typo. 517 throw new Error( 'Property "' + method + '" is not a function' ); 518 } 519 } else if ( typeof method !== 'function' ) { 520 throw new Error( 'Invalid callback. Function or method name expected.' ); 521 } 522 } 523 524 /* Methods */ 525 526 /** 527 * Add a listener to events of a specific event. 528 * 529 * The listener can be a function or the string name of a method; if the latter, then the 530 * name lookup happens at the time the listener is called. 531 * 532 * @param {string} event Type of event to listen to 533 * @param {Function|string} method Function or method name to call when event occurs 534 * @param {Array} [args] Arguments to pass to listener, will be prepended to emitted arguments 535 * @param {Object} [context=null] Context object for function or method call 536 * @throws {Error} Listener argument is not a function or a valid method name 537 * @chainable 538 */ 539 oo.EventEmitter.prototype.on = function ( event, method, args, context ) { 540 var bindings; 541 542 validateMethod( method, context ); 543 544 if ( hasOwn.call( this.bindings, event ) ) { 545 bindings = this.bindings[event]; 546 } else { 547 // Auto-initialize bindings list 548 bindings = this.bindings[event] = []; 549 } 550 // Add binding 551 bindings.push( { 552 method: method, 553 args: args, 554 context: ( arguments.length < 4 ) ? null : context 555 } ); 556 return this; 557 }; 558 559 /** 560 * Add a one-time listener to a specific event. 561 * 562 * @param {string} event Type of event to listen to 563 * @param {Function} listener Listener to call when event occurs 564 * @chainable 565 */ 566 oo.EventEmitter.prototype.once = function ( event, listener ) { 567 var eventEmitter = this, 568 listenerWrapper = function () { 569 eventEmitter.off( event, listenerWrapper ); 570 listener.apply( eventEmitter, Array.prototype.slice.call( arguments, 0 ) ); 571 }; 572 return this.on( event, listenerWrapper ); 573 }; 574 575 /** 576 * Remove a specific listener from a specific event. 577 * 578 * @param {string} event Type of event to remove listener from 579 * @param {Function|string} [method] Listener to remove. Must be in the same form as was passed 580 * to "on". Omit to remove all listeners. 581 * @param {Object} [context=null] Context object function or method call 582 * @chainable 583 * @throws {Error} Listener argument is not a function or a valid method name 584 */ 585 oo.EventEmitter.prototype.off = function ( event, method, context ) { 586 var i, bindings; 587 588 if ( arguments.length === 1 ) { 589 // Remove all bindings for event 590 delete this.bindings[event]; 591 return this; 592 } 593 594 validateMethod( method, context ); 595 596 if ( !( event in this.bindings ) || !this.bindings[event].length ) { 597 // No matching bindings 598 return this; 599 } 600 601 // Default to null context 602 if ( arguments.length < 3 ) { 603 context = null; 604 } 605 606 // Remove matching handlers 607 bindings = this.bindings[event]; 608 i = bindings.length; 609 while ( i-- ) { 610 if ( bindings[i].method === method && bindings[i].context === context ) { 611 bindings.splice( i, 1 ); 612 } 613 } 614 615 // Cleanup if now empty 616 if ( bindings.length === 0 ) { 617 delete this.bindings[event]; 618 } 619 return this; 620 }; 621 622 /** 623 * Emit an event. 624 * 625 * TODO: Should this be chainable? What is the usefulness of the boolean 626 * return value here? 627 * 628 * @param {string} event Type of event 629 * @param {Mixed} args First in a list of variadic arguments passed to event handler (optional) 630 * @return {boolean} If event was handled by at least one listener 631 */ 632 oo.EventEmitter.prototype.emit = function ( event ) { 633 var i, len, binding, bindings, args, method; 634 635 if ( event in this.bindings ) { 636 // Slicing ensures that we don't get tripped up by event handlers that add/remove bindings 637 bindings = this.bindings[event].slice(); 638 args = Array.prototype.slice.call( arguments, 1 ); 639 for ( i = 0, len = bindings.length; i < len; i++ ) { 640 binding = bindings[i]; 641 if ( typeof binding.method === 'string' ) { 642 // Lookup method by name (late binding) 643 method = binding.context[ binding.method ]; 644 } else { 645 method = binding.method; 646 } 647 method.apply( 648 binding.context, 649 binding.args ? binding.args.concat( args ) : args 650 ); 651 } 652 return true; 653 } 654 return false; 655 }; 656 657 /** 658 * Connect event handlers to an object. 659 * 660 * @param {Object} context Object to call methods on when events occur 661 * @param {Object.<string,string>|Object.<string,Function>|Object.<string,Array>} methods List of 662 * event bindings keyed by event name containing either method names, functions or arrays containing 663 * method name or function followed by a list of arguments to be passed to callback before emitted 664 * arguments 665 * @chainable 666 */ 667 oo.EventEmitter.prototype.connect = function ( context, methods ) { 668 var method, args, event; 669 670 for ( event in methods ) { 671 method = methods[event]; 672 // Allow providing additional args 673 if ( Array.isArray( method ) ) { 674 args = method.slice( 1 ); 675 method = method[0]; 676 } else { 677 args = []; 678 } 679 // Add binding 680 this.on( event, method, args, context ); 681 } 682 return this; 683 }; 684 685 /** 686 * Disconnect event handlers from an object. 687 * 688 * @param {Object} context Object to disconnect methods from 689 * @param {Object.<string,string>|Object.<string,Function>|Object.<string,Array>} [methods] List of 690 * event bindings keyed by event name. Values can be either method names or functions, but must be 691 * consistent with those used in the corresponding call to "connect". 692 * @chainable 693 */ 694 oo.EventEmitter.prototype.disconnect = function ( context, methods ) { 695 var i, event, bindings; 696 697 if ( methods ) { 698 // Remove specific connections to the context 699 for ( event in methods ) { 700 this.off( event, methods[event], context ); 701 } 702 } else { 703 // Remove all connections to the context 704 for ( event in this.bindings ) { 705 bindings = this.bindings[event]; 706 i = bindings.length; 707 while ( i-- ) { 708 // bindings[i] may have been removed by the previous step's 709 // this.off so check it still exists 710 if ( bindings[i] && bindings[i].context === context ) { 711 this.off( event, bindings[i].method, context ); 712 } 713 } 714 } 715 } 716 717 return this; 718 }; 719 720 }() ); 721 722 /*global hasOwn */ 723 724 /** 725 * @class OO.Registry 726 * @mixins OO.EventEmitter 727 * 728 * @constructor 729 */ 730 oo.Registry = function OoRegistry() { 731 // Mixin constructors 732 oo.EventEmitter.call( this ); 733 734 // Properties 735 this.registry = {}; 736 }; 737 738 /* Inheritance */ 739 740 oo.mixinClass( oo.Registry, oo.EventEmitter ); 741 742 /* Events */ 743 744 /** 745 * @event register 746 * @param {string} name 747 * @param {Mixed} data 748 */ 749 750 /* Methods */ 751 752 /** 753 * Associate one or more symbolic names with some data. 754 * 755 * Only the base name will be registered, overriding any existing entry with the same base name. 756 * 757 * @param {string|string[]} name Symbolic name or list of symbolic names 758 * @param {Mixed} data Data to associate with symbolic name 759 * @fires register 760 * @throws {Error} Name argument must be a string or array 761 */ 762 oo.Registry.prototype.register = function ( name, data ) { 763 var i, len; 764 if ( typeof name === 'string' ) { 765 this.registry[name] = data; 766 this.emit( 'register', name, data ); 767 } else if ( Array.isArray( name ) ) { 768 for ( i = 0, len = name.length; i < len; i++ ) { 769 this.register( name[i], data ); 770 } 771 } else { 772 throw new Error( 'Name must be a string or array, cannot be a ' + typeof name ); 773 } 774 }; 775 776 /** 777 * Get data for a given symbolic name. 778 * 779 * Lookups are done using the base name. 780 * 781 * @param {string} name Symbolic name 782 * @return {Mixed|undefined} Data associated with symbolic name 783 */ 784 oo.Registry.prototype.lookup = function ( name ) { 785 if ( hasOwn.call( this.registry, name ) ) { 786 return this.registry[name]; 787 } 788 }; 789 790 /** 791 * @class OO.Factory 792 * @extends OO.Registry 793 * 794 * @constructor 795 */ 796 oo.Factory = function OoFactory() { 797 oo.Factory.parent.call( this ); 798 799 // Properties 800 this.entries = []; 801 }; 802 803 /* Inheritance */ 804 805 oo.inheritClass( oo.Factory, oo.Registry ); 806 807 /* Methods */ 808 809 /** 810 * Register a constructor with the factory. 811 * 812 * Classes must have a static `name` property to be registered. 813 * 814 * function MyClass() {}; 815 * OO.initClass( MyClass ); 816 * // Adds a static property to the class defining a symbolic name 817 * MyClass.static.name = 'mine'; 818 * // Registers class with factory, available via symbolic name 'mine' 819 * factory.register( MyClass ); 820 * 821 * @param {Function} constructor Constructor to use when creating object 822 * @throws {Error} Name must be a string and must not be empty 823 * @throws {Error} Constructor must be a function 824 */ 825 oo.Factory.prototype.register = function ( constructor ) { 826 var name; 827 828 if ( typeof constructor !== 'function' ) { 829 throw new Error( 'constructor must be a function, cannot be a ' + typeof constructor ); 830 } 831 name = constructor.static && constructor.static.name; 832 if ( typeof name !== 'string' || name === '' ) { 833 throw new Error( 'Name must be a string and must not be empty' ); 834 } 835 this.entries.push( name ); 836 837 oo.Factory.parent.prototype.register.call( this, name, constructor ); 838 }; 839 840 /** 841 * Create an object based on a name. 842 * 843 * Name is used to look up the constructor to use, while all additional arguments are passed to the 844 * constructor directly, so leaving one out will pass an undefined to the constructor. 845 * 846 * @param {string} name Object name 847 * @param {Mixed...} [args] Arguments to pass to the constructor 848 * @return {Object} The new object 849 * @throws {Error} Unknown object name 850 */ 851 oo.Factory.prototype.create = function ( name ) { 852 var args, obj, 853 constructor = this.lookup( name ); 854 855 if ( !constructor ) { 856 throw new Error( 'No class registered by that name: ' + name ); 857 } 858 859 // Convert arguments to array and shift the first argument (name) off 860 args = Array.prototype.slice.call( arguments, 1 ); 861 862 // We can't use the "new" operator with .apply directly because apply needs a 863 // context. So instead just do what "new" does: create an object that inherits from 864 // the constructor's prototype (which also makes it an "instanceof" the constructor), 865 // then invoke the constructor with the object as context, and return it (ignoring 866 // the constructor's return value). 867 obj = Object.create( constructor.prototype ); 868 constructor.apply( obj, args ); 869 return obj; 870 }; 871 872 /*jshint node:true */ 873 if ( typeof module !== 'undefined' && module.exports ) { 874 module.exports = oo; 875 } else { 876 global.OO = oo; 877 } 878 879 }( this ) );
title
Description
Body
title
Description
Body
title
Description
Body
title
Body
Generated: Fri Nov 28 14:03:12 2014 | Cross-referenced by PHPXref 0.7.1 |