API Docs for: 3.17.2
Show:

File: oop/js/oop.js

  1. /**
  2. Adds object inheritance and manipulation utilities to the YUI instance. This
  3. module is required by most YUI components.
  4.  
  5. @module oop
  6. **/
  7.  
  8. var L = Y.Lang,
  9. A = Y.Array,
  10. OP = Object.prototype,
  11. CLONE_MARKER = '_~yuim~_',
  12.  
  13. hasOwn = OP.hasOwnProperty,
  14. toString = OP.toString;
  15.  
  16. /**
  17. Calls the specified _action_ method on _o_ if it exists. Otherwise, if _o_ is an
  18. array, calls the _action_ method on `Y.Array`, or if _o_ is an object, calls the
  19. _action_ method on `Y.Object`.
  20.  
  21. If _o_ is an array-like object, it will be coerced to an array.
  22.  
  23. This is intended to be used with array/object iteration methods that share
  24. signatures, such as `each()`, `some()`, etc.
  25.  
  26. @method dispatch
  27. @param {Object} o Array or object to dispatch to.
  28. @param {Function} f Iteration callback.
  29. @param {Mixed} f.value Value being iterated.
  30. @param {Mixed} f.key Current object key or array index.
  31. @param {Mixed} f.object Object or array being iterated.
  32. @param {Object} c `this` object to bind the iteration callback to.
  33. @param {Boolean} proto If `true`, prototype properties of objects will be
  34. iterated.
  35. @param {String} action Function name to be dispatched on _o_. For example:
  36. 'some', 'each', etc.
  37. @private
  38. @return {Mixed} Returns the value returned by the chosen iteration action, which
  39. varies.
  40. **/
  41. function dispatch(o, f, c, proto, action) {
  42. if (o && o[action] && o !== Y) {
  43. return o[action].call(o, f, c);
  44. } else {
  45. switch (A.test(o)) {
  46. case 1:
  47. return A[action](o, f, c);
  48. case 2:
  49. return A[action](Y.Array(o, 0, true), f, c);
  50. default:
  51. return Y.Object[action](o, f, c, proto);
  52. }
  53. }
  54. }
  55.  
  56. /**
  57. Augments the _receiver_ with prototype properties from the _supplier_. The
  58. receiver may be a constructor function or an object. The supplier must be a
  59. constructor function.
  60.  
  61. If the _receiver_ is an object, then the _supplier_ constructor will be called
  62. immediately after _receiver_ is augmented, with _receiver_ as the `this` object.
  63.  
  64. If the _receiver_ is a constructor function, then all prototype methods of
  65. _supplier_ that are copied to _receiver_ will be sequestered, and the
  66. _supplier_ constructor will not be called immediately. The first time any
  67. sequestered method is called on the _receiver_'s prototype, all sequestered
  68. methods will be immediately copied to the _receiver_'s prototype, the
  69. _supplier_'s constructor will be executed, and finally the newly unsequestered
  70. method that was called will be executed.
  71.  
  72. This sequestering logic sounds like a bunch of complicated voodoo, but it makes
  73. it cheap to perform frequent augmentation by ensuring that suppliers'
  74. constructors are only called if a supplied method is actually used. If none of
  75. the supplied methods is ever used, then there's no need to take the performance
  76. hit of calling the _supplier_'s constructor.
  77.  
  78. @method augment
  79. @param {Function|Object} receiver Object or function to be augmented.
  80. @param {Function} supplier Function that supplies the prototype properties with
  81. which to augment the _receiver_.
  82. @param {Boolean} [overwrite=false] If `true`, properties already on the receiver
  83. will be overwritten if found on the supplier's prototype.
  84. @param {String[]} [whitelist] An array of property names. If specified,
  85. only the whitelisted prototype properties will be applied to the receiver, and
  86. all others will be ignored.
  87. @param {Array|any} [args] Argument or array of arguments to pass to the
  88. supplier's constructor when initializing.
  89. @return {Function} Augmented object.
  90. @for YUI
  91. **/
  92. Y.augment = function (receiver, supplier, overwrite, whitelist, args) {
  93. var rProto = receiver.prototype,
  94. sequester = rProto && supplier,
  95. sProto = supplier.prototype,
  96. to = rProto || receiver,
  97.  
  98. copy,
  99. newPrototype,
  100. replacements,
  101. sequestered,
  102. unsequester;
  103.  
  104. args = args ? Y.Array(args) : [];
  105.  
  106. if (sequester) {
  107. newPrototype = {};
  108. replacements = {};
  109. sequestered = {};
  110.  
  111. copy = function (value, key) {
  112. if (overwrite || !(key in rProto)) {
  113. if (toString.call(value) === '[object Function]') {
  114. sequestered[key] = value;
  115.  
  116. newPrototype[key] = replacements[key] = function () {
  117. return unsequester(this, value, arguments);
  118. };
  119. } else {
  120. newPrototype[key] = value;
  121. }
  122. }
  123. };
  124.  
  125. unsequester = function (instance, fn, fnArgs) {
  126. // Unsequester all sequestered functions.
  127. for (var key in sequestered) {
  128. if (hasOwn.call(sequestered, key)
  129. && instance[key] === replacements[key]) {
  130.  
  131. instance[key] = sequestered[key];
  132. }
  133. }
  134.  
  135. // Execute the supplier constructor.
  136. supplier.apply(instance, args);
  137.  
  138. // Finally, execute the original sequestered function.
  139. return fn.apply(instance, fnArgs);
  140. };
  141.  
  142. if (whitelist) {
  143. Y.Array.each(whitelist, function (name) {
  144. if (name in sProto) {
  145. copy(sProto[name], name);
  146. }
  147. });
  148. } else {
  149. Y.Object.each(sProto, copy, null, true);
  150. }
  151. }
  152.  
  153. Y.mix(to, newPrototype || sProto, overwrite, whitelist);
  154.  
  155. if (!sequester) {
  156. supplier.apply(to, args);
  157. }
  158.  
  159. return receiver;
  160. };
  161.  
  162. /**
  163. * Copies object properties from the supplier to the receiver. If the target has
  164. * the property, and the property is an object, the target object will be
  165. * augmented with the supplier's value.
  166. *
  167. * @method aggregate
  168. * @param {Object} receiver Object to receive the augmentation.
  169. * @param {Object} supplier Object that supplies the properties with which to
  170. * augment the receiver.
  171. * @param {Boolean} [overwrite=false] If `true`, properties already on the receiver
  172. * will be overwritten if found on the supplier.
  173. * @param {String[]} [whitelist] Whitelist. If supplied, only properties in this
  174. * list will be applied to the receiver.
  175. * @return {Object} Augmented object.
  176. */
  177. Y.aggregate = function(r, s, ov, wl) {
  178. return Y.mix(r, s, ov, wl, 0, true);
  179. };
  180.  
  181. /**
  182. * Utility to set up the prototype, constructor and superclass properties to
  183. * support an inheritance strategy that can chain constructors and methods.
  184. * Static members will not be inherited.
  185. *
  186. * @method extend
  187. * @param {function} r the object to modify.
  188. * @param {function} s the object to inherit.
  189. * @param {object} px prototype properties to add/override.
  190. * @param {object} sx static properties to add/override.
  191. * @return {object} the extended object.
  192. */
  193. Y.extend = function(r, s, px, sx) {
  194. if (!s || !r) {
  195. Y.error('extend failed, verify dependencies');
  196. }
  197.  
  198. var sp = s.prototype, rp = Y.Object(sp);
  199. r.prototype = rp;
  200.  
  201. rp.constructor = r;
  202. r.superclass = sp;
  203.  
  204. // assign constructor property
  205. if (s != Object && sp.constructor == OP.constructor) {
  206. sp.constructor = s;
  207. }
  208.  
  209. // add prototype overrides
  210. if (px) {
  211. Y.mix(rp, px, true);
  212. }
  213.  
  214. // add object overrides
  215. if (sx) {
  216. Y.mix(r, sx, true);
  217. }
  218.  
  219. return r;
  220. };
  221.  
  222. /**
  223. * Executes the supplied function for each item in
  224. * a collection. Supports arrays, objects, and
  225. * NodeLists
  226. * @method each
  227. * @param {object} o the object to iterate.
  228. * @param {function} f the function to execute. This function
  229. * receives the value, key, and object as parameters.
  230. * @param {object} c the execution context for the function.
  231. * @param {boolean} proto if true, prototype properties are
  232. * iterated on objects.
  233. * @return {YUI} the YUI instance.
  234. */
  235. Y.each = function(o, f, c, proto) {
  236. return dispatch(o, f, c, proto, 'each');
  237. };
  238.  
  239. /**
  240. * Executes the supplied function for each item in
  241. * a collection. The operation stops if the function
  242. * returns true. Supports arrays, objects, and
  243. * NodeLists.
  244. * @method some
  245. * @param {object} o the object to iterate.
  246. * @param {function} f the function to execute. This function
  247. * receives the value, key, and object as parameters.
  248. * @param {object} c the execution context for the function.
  249. * @param {boolean} proto if true, prototype properties are
  250. * iterated on objects.
  251. * @return {boolean} true if the function ever returns true,
  252. * false otherwise.
  253. */
  254. Y.some = function(o, f, c, proto) {
  255. return dispatch(o, f, c, proto, 'some');
  256. };
  257.  
  258. /**
  259. Deep object/array copy. Function clones are actually wrappers around the
  260. original function. Array-like objects are treated as arrays. Primitives are
  261. returned untouched. Optionally, a function can be provided to handle other data
  262. types, filter keys, validate values, etc.
  263.  
  264. **Note:** Cloning a non-trivial object is a reasonably heavy operation, due to
  265. the need to recursively iterate down non-primitive properties. Clone should be
  266. used only when a deep clone down to leaf level properties is explicitly
  267. required. This method will also
  268.  
  269. In many cases (for example, when trying to isolate objects used as hashes for
  270. configuration properties), a shallow copy, using `Y.merge()` is normally
  271. sufficient. If more than one level of isolation is required, `Y.merge()` can be
  272. used selectively at each level which needs to be isolated from the original
  273. without going all the way to leaf properties.
  274.  
  275. @method clone
  276. @param {object} o what to clone.
  277. @param {boolean} safe if true, objects will not have prototype items from the
  278. source. If false, they will. In this case, the original is initially
  279. protected, but the clone is not completely immune from changes to the source
  280. object prototype. Also, cloned prototype items that are deleted from the
  281. clone will result in the value of the source prototype being exposed. If
  282. operating on a non-safe clone, items should be nulled out rather than
  283. deleted.
  284. @param {function} f optional function to apply to each item in a collection; it
  285. will be executed prior to applying the value to the new object.
  286. Return false to prevent the copy.
  287. @param {object} c optional execution context for f.
  288. @param {object} owner Owner object passed when clone is iterating an object.
  289. Used to set up context for cloned functions.
  290. @param {object} cloned hash of previously cloned objects to avoid multiple
  291. clones.
  292. @return {Array|Object} the cloned object.
  293. **/
  294. Y.clone = function(o, safe, f, c, owner, cloned) {
  295. var o2, marked, stamp;
  296.  
  297. // Does not attempt to clone:
  298. //
  299. // * Non-typeof-object values, "primitive" values don't need cloning.
  300. //
  301. // * YUI instances, cloning complex object like YUI instances is not
  302. // advised, this is like cloning the world.
  303. //
  304. // * DOM nodes (#2528250), common host objects like DOM nodes cannot be
  305. // "subclassed" in Firefox and old versions of IE. Trying to use
  306. // `Object.create()` or `Y.extend()` on a DOM node will throw an error in
  307. // these browsers.
  308. //
  309. // Instad, the passed-in `o` will be return as-is when it matches one of the
  310. // above criteria.
  311. if (!L.isObject(o) ||
  312. Y.instanceOf(o, YUI) ||
  313. (o.addEventListener || o.attachEvent)) {
  314.  
  315. return o;
  316. }
  317.  
  318. marked = cloned || {};
  319.  
  320. switch (L.type(o)) {
  321. case 'date':
  322. return new Date(o);
  323. case 'regexp':
  324. // if we do this we need to set the flags too
  325. // return new RegExp(o.source);
  326. return o;
  327. case 'function':
  328. // o2 = Y.bind(o, owner);
  329. // break;
  330. return o;
  331. case 'array':
  332. o2 = [];
  333. break;
  334. default:
  335.  
  336. // #2528250 only one clone of a given object should be created.
  337. if (o[CLONE_MARKER]) {
  338. return marked[o[CLONE_MARKER]];
  339. }
  340.  
  341. stamp = Y.guid();
  342.  
  343. o2 = (safe) ? {} : Y.Object(o);
  344.  
  345. o[CLONE_MARKER] = stamp;
  346. marked[stamp] = o;
  347. }
  348.  
  349. Y.each(o, function(v, k) {
  350. if ((k || k === 0) && (!f || (f.call(c || this, v, k, this, o) !== false))) {
  351. if (k !== CLONE_MARKER) {
  352. if (k == 'prototype') {
  353. // skip the prototype
  354. // } else if (o[k] === o) {
  355. // this[k] = this;
  356. } else {
  357. this[k] =
  358. Y.clone(v, safe, f, c, owner || o, marked);
  359. }
  360. }
  361. }
  362. }, o2);
  363.  
  364. if (!cloned) {
  365. Y.Object.each(marked, function(v, k) {
  366. if (v[CLONE_MARKER]) {
  367. try {
  368. delete v[CLONE_MARKER];
  369. } catch (e) {
  370. v[CLONE_MARKER] = null;
  371. }
  372. }
  373. }, this);
  374. marked = null;
  375. }
  376.  
  377. return o2;
  378. };
  379.  
  380. /**
  381. * Returns a function that will execute the supplied function in the
  382. * supplied object's context, optionally adding any additional
  383. * supplied parameters to the beginning of the arguments collection the
  384. * supplied to the function.
  385. *
  386. * @method bind
  387. * @param {Function|String} f the function to bind, or a function name
  388. * to execute on the context object.
  389. * @param {object} c the execution context.
  390. * @param {any} args* 0..n arguments to include before the arguments the
  391. * function is executed with.
  392. * @return {function} the wrapped function.
  393. */
  394. Y.bind = function(f, c) {
  395. var xargs = arguments.length > 2 ?
  396. Y.Array(arguments, 2, true) : null;
  397. return function() {
  398. var fn = L.isString(f) ? c[f] : f,
  399. args = (xargs) ?
  400. xargs.concat(Y.Array(arguments, 0, true)) : arguments;
  401. return fn.apply(c || fn, args);
  402. };
  403. };
  404.  
  405. /**
  406. * Returns a function that will execute the supplied function in the
  407. * supplied object's context, optionally adding any additional
  408. * supplied parameters to the end of the arguments the function
  409. * is executed with.
  410. *
  411. * @method rbind
  412. * @param {Function|String} f the function to bind, or a function name
  413. * to execute on the context object.
  414. * @param {object} c the execution context.
  415. * @param {any} args* 0..n arguments to append to the end of
  416. * arguments collection supplied to the function.
  417. * @return {function} the wrapped function.
  418. */
  419. Y.rbind = function(f, c) {
  420. var xargs = arguments.length > 2 ? Y.Array(arguments, 2, true) : null;
  421. return function() {
  422. var fn = L.isString(f) ? c[f] : f,
  423. args = (xargs) ?
  424. Y.Array(arguments, 0, true).concat(xargs) : arguments;
  425. return fn.apply(c || fn, args);
  426. };
  427. };
  428.