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