attribute-base-debug.js 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197
  1. /*
  2. YUI 3.4.1 (build 4118)
  3. Copyright 2011 Yahoo! Inc. All rights reserved.
  4. Licensed under the BSD License.
  5. http://yuilibrary.com/license/
  6. */
  7. YUI.add('attribute-base', function(Y) {
  8. /**
  9. * The State class maintains state for a collection of named items, with
  10. * a varying number of properties defined.
  11. *
  12. * It avoids the need to create a separate class for the item, and separate instances
  13. * of these classes for each item, by storing the state in a 2 level hash table,
  14. * improving performance when the number of items is likely to be large.
  15. *
  16. * @constructor
  17. * @class State
  18. */
  19. Y.State = function() {
  20. /**
  21. * Hash of attributes
  22. * @property data
  23. */
  24. this.data = {};
  25. };
  26. Y.State.prototype = {
  27. /**
  28. * Adds a property to an item.
  29. *
  30. * @method add
  31. * @param name {String} The name of the item.
  32. * @param key {String} The name of the property.
  33. * @param val {Any} The value of the property.
  34. */
  35. add : function(name, key, val) {
  36. var d = this.data;
  37. d[key] = d[key] || {};
  38. d[key][name] = val;
  39. },
  40. /**
  41. * Adds multiple properties to an item.
  42. *
  43. * @method addAll
  44. * @param name {String} The name of the item.
  45. * @param o {Object} A hash of property/value pairs.
  46. */
  47. addAll: function(name, o) {
  48. var key;
  49. for (key in o) {
  50. if (o.hasOwnProperty(key)) {
  51. this.add(name, key, o[key]);
  52. }
  53. }
  54. },
  55. /**
  56. * Removes a property from an item.
  57. *
  58. * @method remove
  59. * @param name {String} The name of the item.
  60. * @param key {String} The property to remove.
  61. */
  62. remove: function(name, key) {
  63. var d = this.data;
  64. if (d[key] && (name in d[key])) {
  65. delete d[key][name];
  66. }
  67. },
  68. /**
  69. * Removes multiple properties from an item, or remove the item completely.
  70. *
  71. * @method removeAll
  72. * @param name {String} The name of the item.
  73. * @param o {Object|Array} Collection of properties to delete. If not provided, the entire item is removed.
  74. */
  75. removeAll: function(name, o) {
  76. var d = this.data;
  77. Y.each(o || d, function(v, k) {
  78. if(Y.Lang.isString(k)) {
  79. this.remove(name, k);
  80. } else {
  81. this.remove(name, v);
  82. }
  83. }, this);
  84. },
  85. /**
  86. * For a given item, returns the value of the property requested, or undefined if not found.
  87. *
  88. * @method get
  89. * @param name {String} The name of the item
  90. * @param key {String} Optional. The property value to retrieve.
  91. * @return {Any} The value of the supplied property.
  92. */
  93. get: function(name, key) {
  94. var d = this.data;
  95. return (d[key] && name in d[key]) ? d[key][name] : undefined;
  96. },
  97. /**
  98. * For the given item, returns a disposable object with all of the
  99. * item's property/value pairs.
  100. *
  101. * @method getAll
  102. * @param name {String} The name of the item
  103. * @return {Object} An object with property/value pairs for the item.
  104. */
  105. getAll : function(name) {
  106. var d = this.data, o;
  107. Y.each(d, function(v, k) {
  108. if (name in d[k]) {
  109. o = o || {};
  110. o[k] = v[name];
  111. }
  112. }, this);
  113. return o;
  114. }
  115. };
  116. /**
  117. * The attribute module provides an augmentable Attribute implementation, which
  118. * adds configurable attributes and attribute change events to the class being
  119. * augmented. It also provides a State class, which is used internally by Attribute,
  120. * but can also be used independently to provide a name/property/value data structure to
  121. * store state.
  122. *
  123. * @module attribute
  124. */
  125. /**
  126. * The attribute-base submodule provides core attribute handling support, with everything
  127. * aside from complex attribute handling in the provider's constructor.
  128. *
  129. * @module attribute
  130. * @submodule attribute-base
  131. */
  132. var O = Y.Object,
  133. Lang = Y.Lang,
  134. EventTarget = Y.EventTarget,
  135. DOT = ".",
  136. CHANGE = "Change",
  137. // Externally configurable props
  138. GETTER = "getter",
  139. SETTER = "setter",
  140. READ_ONLY = "readOnly",
  141. WRITE_ONCE = "writeOnce",
  142. INIT_ONLY = "initOnly",
  143. VALIDATOR = "validator",
  144. VALUE = "value",
  145. VALUE_FN = "valueFn",
  146. BROADCAST = "broadcast",
  147. LAZY_ADD = "lazyAdd",
  148. BYPASS_PROXY = "_bypassProxy",
  149. // Used for internal state management
  150. ADDED = "added",
  151. INITIALIZING = "initializing",
  152. INIT_VALUE = "initValue",
  153. PUBLISHED = "published",
  154. DEF_VALUE = "defaultValue",
  155. LAZY = "lazy",
  156. IS_LAZY_ADD = "isLazyAdd",
  157. INVALID_VALUE,
  158. MODIFIABLE = {};
  159. // Properties which can be changed after the attribute has been added.
  160. MODIFIABLE[READ_ONLY] = 1;
  161. MODIFIABLE[WRITE_ONCE] = 1;
  162. MODIFIABLE[GETTER] = 1;
  163. MODIFIABLE[BROADCAST] = 1;
  164. /**
  165. * <p>
  166. * Attribute provides configurable attribute support along with attribute change events. It is designed to be
  167. * augmented on to a host class, and provides the host with the ability to configure attributes to store and retrieve state,
  168. * along with attribute change events.
  169. * </p>
  170. * <p>For example, attributes added to the host can be configured:</p>
  171. * <ul>
  172. * <li>As read only.</li>
  173. * <li>As write once.</li>
  174. * <li>With a setter function, which can be used to manipulate
  175. * values passed to Attribute's <a href="#method_set">set</a> method, before they are stored.</li>
  176. * <li>With a getter function, which can be used to manipulate stored values,
  177. * before they are returned by Attribute's <a href="#method_get">get</a> method.</li>
  178. * <li>With a validator function, to validate values before they are stored.</li>
  179. * </ul>
  180. *
  181. * <p>See the <a href="#method_addAttr">addAttr</a> method, for the complete set of configuration
  182. * options available for attributes</p>.
  183. *
  184. * <p><strong>NOTE:</strong> Most implementations will be better off extending the <a href="Base.html">Base</a> class,
  185. * instead of augmenting Attribute directly. Base augments Attribute and will handle the initial configuration
  186. * of attributes for derived classes, accounting for values passed into the constructor.</p>
  187. *
  188. * @class Attribute
  189. * @param attrs {Object} The attributes to add during construction (passed through to <a href="#method_addAttrs">addAttrs</a>). These can also be defined on the constructor being augmented with Attribute by defining the ATTRS property on the constructor.
  190. * @param values {Object} The initial attribute values to apply (passed through to <a href="#method_addAttrs">addAttrs</a>). These are not merged/cloned. The caller is responsible for isolating user provided values if required.
  191. * @param lazy {boolean} Whether or not to add attributes lazily (passed through to <a href="#method_addAttrs">addAttrs</a>).
  192. * @uses EventTarget
  193. */
  194. function Attribute(attrs, values, lazy) {
  195. var host = this; // help compression
  196. // Perf tweak - avoid creating event literals if not required.
  197. host._ATTR_E_FACADE = {};
  198. EventTarget.call(host, {emitFacade:true});
  199. // _conf maintained for backwards compat
  200. host._conf = host._state = new Y.State();
  201. host._stateProxy = host._stateProxy || null;
  202. host._requireAddAttr = host._requireAddAttr || false;
  203. this._initAttrs(attrs, values, lazy);
  204. }
  205. /**
  206. * <p>The value to return from an attribute setter in order to prevent the set from going through.</p>
  207. *
  208. * <p>You can return this value from your setter if you wish to combine validator and setter
  209. * functionality into a single setter function, which either returns the massaged value to be stored or
  210. * Attribute.INVALID_VALUE to prevent invalid values from being stored.</p>
  211. *
  212. * @property INVALID_VALUE
  213. * @type Object
  214. * @static
  215. * @final
  216. */
  217. Attribute.INVALID_VALUE = {};
  218. INVALID_VALUE = Attribute.INVALID_VALUE;
  219. /**
  220. * The list of properties which can be configured for
  221. * each attribute (e.g. setter, getter, writeOnce etc.).
  222. *
  223. * This property is used internally as a whitelist for faster
  224. * Y.mix operations.
  225. *
  226. * @property _ATTR_CFG
  227. * @type Array
  228. * @static
  229. * @protected
  230. */
  231. Attribute._ATTR_CFG = [SETTER, GETTER, VALIDATOR, VALUE, VALUE_FN, WRITE_ONCE, READ_ONLY, LAZY_ADD, BROADCAST, BYPASS_PROXY];
  232. Attribute.prototype = {
  233. /**
  234. * <p>
  235. * Adds an attribute with the provided configuration to the host object.
  236. * </p>
  237. * <p>
  238. * The config argument object supports the following properties:
  239. * </p>
  240. *
  241. * <dl>
  242. * <dt>value &#60;Any&#62;</dt>
  243. * <dd>The initial value to set on the attribute</dd>
  244. *
  245. * <dt>valueFn &#60;Function | String&#62;</dt>
  246. * <dd>
  247. * <p>A function, which will return the initial value to set on the attribute. This is useful
  248. * for cases where the attribute configuration is defined statically, but needs to
  249. * reference the host instance ("this") to obtain an initial value. If both the value and valueFn properties are defined,
  250. * the value returned by the valueFn has precedence over the value property, unless it returns undefined, in which
  251. * case the value property is used.</p>
  252. *
  253. * <p>valueFn can also be set to a string, representing the name of the instance method to be used to retrieve the value.</p>
  254. * </dd>
  255. *
  256. * <dt>readOnly &#60;boolean&#62;</dt>
  257. * <dd>Whether or not the attribute is read only. Attributes having readOnly set to true
  258. * cannot be modified by invoking the set method.</dd>
  259. *
  260. * <dt>writeOnce &#60;boolean&#62; or &#60;string&#62;</dt>
  261. * <dd>
  262. * Whether or not the attribute is "write once". Attributes having writeOnce set to true,
  263. * can only have their values set once, be it through the default configuration,
  264. * constructor configuration arguments, or by invoking set.
  265. * <p>The writeOnce attribute can also be set to the string "initOnly", in which case the attribute can only be set during initialization
  266. * (when used with Base, this means it can only be set during construction)</p>
  267. * </dd>
  268. *
  269. * <dt>setter &#60;Function | String&#62;</dt>
  270. * <dd>
  271. * <p>The setter function used to massage or normalize the value passed to the set method for the attribute.
  272. * The value returned by the setter will be the final stored value. Returning
  273. * <a href="#property_Attribute.INVALID_VALUE">Attribute.INVALID_VALUE</a>, from the setter will prevent
  274. * the value from being stored.
  275. * </p>
  276. *
  277. * <p>setter can also be set to a string, representing the name of the instance method to be used as the setter function.</p>
  278. * </dd>
  279. *
  280. * <dt>getter &#60;Function | String&#62;</dt>
  281. * <dd>
  282. * <p>
  283. * The getter function used to massage or normalize the value returned by the get method for the attribute.
  284. * The value returned by the getter function is the value which will be returned to the user when they
  285. * invoke get.
  286. * </p>
  287. *
  288. * <p>getter can also be set to a string, representing the name of the instance method to be used as the getter function.</p>
  289. * </dd>
  290. *
  291. * <dt>validator &#60;Function | String&#62;</dt>
  292. * <dd>
  293. * <p>
  294. * The validator function invoked prior to setting the stored value. Returning
  295. * false from the validator function will prevent the value from being stored.
  296. * </p>
  297. *
  298. * <p>validator can also be set to a string, representing the name of the instance method to be used as the validator function.</p>
  299. * </dd>
  300. *
  301. * <dt>broadcast &#60;int&#62;</dt>
  302. * <dd>If and how attribute change events for this attribute should be broadcast. See CustomEvent's <a href="CustomEvent.html#property_broadcast">broadcast</a> property for
  303. * valid values. By default attribute change events are not broadcast.</dd>
  304. *
  305. * <dt>lazyAdd &#60;boolean&#62;</dt>
  306. * <dd>Whether or not to delay initialization of the attribute until the first call to get/set it.
  307. * This flag can be used to over-ride lazy initialization on a per attribute basis, when adding multiple attributes through
  308. * the <a href="#method_addAttrs">addAttrs</a> method.</dd>
  309. *
  310. * </dl>
  311. *
  312. * <p>The setter, getter and validator are invoked with the value and name passed in as the first and second arguments, and with
  313. * the context ("this") set to the host object.</p>
  314. *
  315. * <p>Configuration properties outside of the list mentioned above are considered private properties used internally by attribute, and are not intended for public use.</p>
  316. *
  317. * @method addAttr
  318. *
  319. * @param {String} name The name of the attribute.
  320. * @param {Object} config An object with attribute configuration property/value pairs, specifying the configuration for the attribute.
  321. *
  322. * <p>
  323. * <strong>NOTE:</strong> The configuration object is modified when adding an attribute, so if you need
  324. * to protect the original values, you will need to merge the object.
  325. * </p>
  326. *
  327. * @param {boolean} lazy (optional) Whether or not to add this attribute lazily (on the first call to get/set).
  328. *
  329. * @return {Object} A reference to the host object.
  330. *
  331. * @chainable
  332. */
  333. addAttr: function(name, config, lazy) {
  334. Y.log('Adding attribute: ' + name, 'info', 'attribute');
  335. var host = this, // help compression
  336. state = host._state,
  337. value,
  338. hasValue;
  339. lazy = (LAZY_ADD in config) ? config[LAZY_ADD] : lazy;
  340. if (lazy && !host.attrAdded(name)) {
  341. state.add(name, LAZY, config || {});
  342. state.add(name, ADDED, true);
  343. } else {
  344. if (host.attrAdded(name) && !state.get(name, IS_LAZY_ADD)) { Y.log('Attribute: ' + name + ' already exists. Cannot add it again without removing it first', 'warn', 'attribute'); }
  345. if (!host.attrAdded(name) || state.get(name, IS_LAZY_ADD)) {
  346. config = config || {};
  347. hasValue = (VALUE in config);
  348. if (config.readOnly && !hasValue) { Y.log('readOnly attribute: ' + name + ', added without an initial value. Value will be set on initial call to set', 'warn', 'attribute');}
  349. if(hasValue) {
  350. // We'll go through set, don't want to set value in config directly
  351. value = config.value;
  352. delete config.value;
  353. }
  354. config.added = true;
  355. config.initializing = true;
  356. state.addAll(name, config);
  357. if (hasValue) {
  358. // Go through set, so that raw values get normalized/validated
  359. host.set(name, value);
  360. }
  361. state.remove(name, INITIALIZING);
  362. }
  363. }
  364. return host;
  365. },
  366. /**
  367. * Checks if the given attribute has been added to the host
  368. *
  369. * @method attrAdded
  370. * @param {String} name The name of the attribute to check.
  371. * @return {boolean} true if an attribute with the given name has been added, false if it hasn't. This method will return true for lazily added attributes.
  372. */
  373. attrAdded: function(name) {
  374. return !!this._state.get(name, ADDED);
  375. },
  376. /**
  377. * Updates the configuration of an attribute which has already been added.
  378. * <p>
  379. * The properties which can be modified through this interface are limited
  380. * to the following subset of attributes, which can be safely modified
  381. * after a value has already been set on the attribute: readOnly, writeOnce,
  382. * broadcast and getter.
  383. * </p>
  384. * @method modifyAttr
  385. * @param {String} name The name of the attribute whose configuration is to be updated.
  386. * @param {Object} config An object with configuration property/value pairs, specifying the configuration properties to modify.
  387. */
  388. modifyAttr: function(name, config) {
  389. var host = this, // help compression
  390. prop, state;
  391. if (host.attrAdded(name)) {
  392. if (host._isLazyAttr(name)) {
  393. host._addLazyAttr(name);
  394. }
  395. state = host._state;
  396. for (prop in config) {
  397. if (MODIFIABLE[prop] && config.hasOwnProperty(prop)) {
  398. state.add(name, prop, config[prop]);
  399. // If we reconfigured broadcast, need to republish
  400. if (prop === BROADCAST) {
  401. state.remove(name, PUBLISHED);
  402. }
  403. }
  404. }
  405. }
  406. if (!host.attrAdded(name)) {Y.log('Attribute modifyAttr:' + name + ' has not been added. Use addAttr to add the attribute', 'warn', 'attribute');}
  407. },
  408. /**
  409. * Removes an attribute from the host object
  410. *
  411. * @method removeAttr
  412. * @param {String} name The name of the attribute to be removed.
  413. */
  414. removeAttr: function(name) {
  415. this._state.removeAll(name);
  416. },
  417. /**
  418. * Returns the current value of the attribute. If the attribute
  419. * has been configured with a 'getter' function, this method will delegate
  420. * to the 'getter' to obtain the value of the attribute.
  421. *
  422. * @method get
  423. *
  424. * @param {String} name The name of the attribute. If the value of the attribute is an Object,
  425. * dot notation can be used to obtain the value of a property of the object (e.g. <code>get("x.y.z")</code>)
  426. *
  427. * @return {Any} The value of the attribute
  428. */
  429. get : function(name) {
  430. return this._getAttr(name);
  431. },
  432. /**
  433. * Checks whether or not the attribute is one which has been
  434. * added lazily and still requires initialization.
  435. *
  436. * @method _isLazyAttr
  437. * @private
  438. * @param {String} name The name of the attribute
  439. * @return {boolean} true if it's a lazily added attribute, false otherwise.
  440. */
  441. _isLazyAttr: function(name) {
  442. return this._state.get(name, LAZY);
  443. },
  444. /**
  445. * Finishes initializing an attribute which has been lazily added.
  446. *
  447. * @method _addLazyAttr
  448. * @private
  449. * @param {Object} name The name of the attribute
  450. */
  451. _addLazyAttr: function(name) {
  452. var state = this._state,
  453. lazyCfg = state.get(name, LAZY);
  454. state.add(name, IS_LAZY_ADD, true);
  455. state.remove(name, LAZY);
  456. this.addAttr(name, lazyCfg);
  457. },
  458. /**
  459. * Sets the value of an attribute.
  460. *
  461. * @method set
  462. * @chainable
  463. *
  464. * @param {String} name The name of the attribute. If the
  465. * current value of the attribute is an Object, dot notation can be used
  466. * to set the value of a property within the object (e.g. <code>set("x.y.z", 5)</code>).
  467. *
  468. * @param {Any} value The value to set the attribute to.
  469. *
  470. * @param {Object} opts (Optional) Optional event data to be mixed into
  471. * the event facade passed to subscribers of the attribute's change event. This
  472. * can be used as a flexible way to identify the source of a call to set, allowing
  473. * the developer to distinguish between set called internally by the host, vs.
  474. * set called externally by the application developer.
  475. *
  476. * @return {Object} A reference to the host object.
  477. */
  478. set : function(name, val, opts) {
  479. return this._setAttr(name, val, opts);
  480. },
  481. /**
  482. * Resets the attribute (or all attributes) to its initial value, as long as
  483. * the attribute is not readOnly, or writeOnce.
  484. *
  485. * @method reset
  486. * @param {String} name Optional. The name of the attribute to reset. If omitted, all attributes are reset.
  487. * @return {Object} A reference to the host object.
  488. * @chainable
  489. */
  490. reset : function(name) {
  491. var host = this, // help compression
  492. added;
  493. if (name) {
  494. if (host._isLazyAttr(name)) {
  495. host._addLazyAttr(name);
  496. }
  497. host.set(name, host._state.get(name, INIT_VALUE));
  498. } else {
  499. added = host._state.data.added;
  500. Y.each(added, function(v, n) {
  501. host.reset(n);
  502. }, host);
  503. }
  504. return host;
  505. },
  506. /**
  507. * Allows setting of readOnly/writeOnce attributes. See <a href="#method_set">set</a> for argument details.
  508. *
  509. * @method _set
  510. * @protected
  511. * @chainable
  512. *
  513. * @param {String} name The name of the attribute.
  514. * @param {Any} val The value to set the attribute to.
  515. * @param {Object} opts (Optional) Optional event data to be mixed into
  516. * the event facade passed to subscribers of the attribute's change event.
  517. * @return {Object} A reference to the host object.
  518. */
  519. _set : function(name, val, opts) {
  520. return this._setAttr(name, val, opts, true);
  521. },
  522. /**
  523. * Provides the common implementation for the public get method,
  524. * allowing Attribute hosts to over-ride either method.
  525. *
  526. * See <a href="#method_get">get</a> for argument details.
  527. *
  528. * @method _getAttr
  529. * @protected
  530. * @chainable
  531. *
  532. * @param {String} name The name of the attribute.
  533. * @return {Any} The value of the attribute.
  534. */
  535. _getAttr : function(name) {
  536. var host = this, // help compression
  537. fullName = name,
  538. state = host._state,
  539. path,
  540. getter,
  541. val,
  542. cfg;
  543. if (name.indexOf(DOT) !== -1) {
  544. path = name.split(DOT);
  545. name = path.shift();
  546. }
  547. // On Demand - Should be rare - handles out of order valueFn references
  548. if (host._tCfgs && host._tCfgs[name]) {
  549. cfg = {};
  550. cfg[name] = host._tCfgs[name];
  551. delete host._tCfgs[name];
  552. host._addAttrs(cfg, host._tVals);
  553. }
  554. // Lazy Init
  555. if (host._isLazyAttr(name)) {
  556. host._addLazyAttr(name);
  557. }
  558. val = host._getStateVal(name);
  559. getter = state.get(name, GETTER);
  560. if (getter && !getter.call) {
  561. getter = this[getter];
  562. }
  563. val = (getter) ? getter.call(host, val, fullName) : val;
  564. val = (path) ? O.getValue(val, path) : val;
  565. return val;
  566. },
  567. /**
  568. * Provides the common implementation for the public set and protected _set methods.
  569. *
  570. * See <a href="#method_set">set</a> for argument details.
  571. *
  572. * @method _setAttr
  573. * @protected
  574. * @chainable
  575. *
  576. * @param {String} name The name of the attribute.
  577. * @param {Any} value The value to set the attribute to.
  578. * @param {Object} opts (Optional) Optional event data to be mixed into
  579. * the event facade passed to subscribers of the attribute's change event.
  580. * @param {boolean} force If true, allows the caller to set values for
  581. * readOnly or writeOnce attributes which have already been set.
  582. *
  583. * @return {Object} A reference to the host object.
  584. */
  585. _setAttr : function(name, val, opts, force) {
  586. var allowSet = true,
  587. state = this._state,
  588. stateProxy = this._stateProxy,
  589. data = state.data,
  590. initialSet,
  591. strPath,
  592. path,
  593. currVal,
  594. writeOnce,
  595. initializing;
  596. if (name.indexOf(DOT) !== -1) {
  597. strPath = name;
  598. path = name.split(DOT);
  599. name = path.shift();
  600. }
  601. if (this._isLazyAttr(name)) {
  602. this._addLazyAttr(name);
  603. }
  604. initialSet = (!data.value || !(name in data.value));
  605. if (stateProxy && name in stateProxy && !this._state.get(name, BYPASS_PROXY)) {
  606. // TODO: Value is always set for proxy. Can we do any better? Maybe take a snapshot as the initial value for the first call to set?
  607. initialSet = false;
  608. }
  609. if (this._requireAddAttr && !this.attrAdded(name)) {
  610. Y.log('Set attribute:' + name + ', aborted; Attribute is not configured', 'warn', 'attribute');
  611. } else {
  612. writeOnce = state.get(name, WRITE_ONCE);
  613. initializing = state.get(name, INITIALIZING);
  614. if (!initialSet && !force) {
  615. if (writeOnce) {
  616. Y.log('Set attribute:' + name + ', aborted; Attribute is writeOnce', 'warn', 'attribute');
  617. allowSet = false;
  618. }
  619. if (state.get(name, READ_ONLY)) {
  620. Y.log('Set attribute:' + name + ', aborted; Attribute is readOnly', 'warn', 'attribute');
  621. allowSet = false;
  622. }
  623. }
  624. if (!initializing && !force && writeOnce === INIT_ONLY) {
  625. Y.log('Set attribute:' + name + ', aborted; Attribute is writeOnce: "initOnly"', 'warn', 'attribute');
  626. allowSet = false;
  627. }
  628. if (allowSet) {
  629. // Don't need currVal if initialSet (might fail in custom getter if it always expects a non-undefined/non-null value)
  630. if (!initialSet) {
  631. currVal = this.get(name);
  632. }
  633. if (path) {
  634. val = O.setValue(Y.clone(currVal), path, val);
  635. if (val === undefined) {
  636. Y.log('Set attribute path:' + strPath + ', aborted; Path is invalid', 'warn', 'attribute');
  637. allowSet = false;
  638. }
  639. }
  640. if (allowSet) {
  641. if (initializing) {
  642. this._setAttrVal(name, strPath, currVal, val);
  643. } else {
  644. this._fireAttrChange(name, strPath, currVal, val, opts);
  645. }
  646. }
  647. }
  648. }
  649. return this;
  650. },
  651. /**
  652. * Utility method to help setup the event payload and fire the attribute change event.
  653. *
  654. * @method _fireAttrChange
  655. * @private
  656. * @param {String} attrName The name of the attribute
  657. * @param {String} subAttrName The full path of the property being changed,
  658. * if this is a sub-attribute value being change. Otherwise null.
  659. * @param {Any} currVal The current value of the attribute
  660. * @param {Any} newVal The new value of the attribute
  661. * @param {Object} opts Any additional event data to mix into the attribute change event's event facade.
  662. */
  663. _fireAttrChange : function(attrName, subAttrName, currVal, newVal, opts) {
  664. var host = this,
  665. eventName = attrName + CHANGE,
  666. state = host._state,
  667. facade;
  668. if (!state.get(attrName, PUBLISHED)) {
  669. host.publish(eventName, {
  670. queuable:false,
  671. defaultTargetOnly: true,
  672. defaultFn:host._defAttrChangeFn,
  673. silent:true,
  674. broadcast : state.get(attrName, BROADCAST)
  675. });
  676. state.add(attrName, PUBLISHED, true);
  677. }
  678. facade = (opts) ? Y.merge(opts) : host._ATTR_E_FACADE;
  679. // Not using the single object signature for fire({type:..., newVal:...}), since
  680. // we don't want to override type. Changed to the fire(type, {newVal:...}) signature.
  681. // facade.type = eventName;
  682. facade.attrName = attrName;
  683. facade.subAttrName = subAttrName;
  684. facade.prevVal = currVal;
  685. facade.newVal = newVal;
  686. // host.fire(facade);
  687. host.fire(eventName, facade);
  688. },
  689. /**
  690. * Default function for attribute change events.
  691. *
  692. * @private
  693. * @method _defAttrChangeFn
  694. * @param {EventFacade} e The event object for attribute change events.
  695. */
  696. _defAttrChangeFn : function(e) {
  697. if (!this._setAttrVal(e.attrName, e.subAttrName, e.prevVal, e.newVal)) {
  698. Y.log('State not updated and stopImmediatePropagation called for attribute: ' + e.attrName + ' , value:' + e.newVal, 'warn', 'attribute');
  699. // Prevent "after" listeners from being invoked since nothing changed.
  700. e.stopImmediatePropagation();
  701. } else {
  702. e.newVal = this.get(e.attrName);
  703. }
  704. },
  705. /**
  706. * Gets the stored value for the attribute, from either the
  707. * internal state object, or the state proxy if it exits
  708. *
  709. * @method _getStateVal
  710. * @private
  711. * @param {String} name The name of the attribute
  712. * @return {Any} The stored value of the attribute
  713. */
  714. _getStateVal : function(name) {
  715. var stateProxy = this._stateProxy;
  716. return stateProxy && (name in stateProxy) && !this._state.get(name, BYPASS_PROXY) ? stateProxy[name] : this._state.get(name, VALUE);
  717. },
  718. /**
  719. * Sets the stored value for the attribute, in either the
  720. * internal state object, or the state proxy if it exits
  721. *
  722. * @method _setStateVal
  723. * @private
  724. * @param {String} name The name of the attribute
  725. * @param {Any} value The value of the attribute
  726. */
  727. _setStateVal : function(name, value) {
  728. var stateProxy = this._stateProxy;
  729. if (stateProxy && (name in stateProxy) && !this._state.get(name, BYPASS_PROXY)) {
  730. stateProxy[name] = value;
  731. } else {
  732. this._state.add(name, VALUE, value);
  733. }
  734. },
  735. /**
  736. * Updates the stored value of the attribute in the privately held State object,
  737. * if validation and setter passes.
  738. *
  739. * @method _setAttrVal
  740. * @private
  741. * @param {String} attrName The attribute name.
  742. * @param {String} subAttrName The sub-attribute name, if setting a sub-attribute property ("x.y.z").
  743. * @param {Any} prevVal The currently stored value of the attribute.
  744. * @param {Any} newVal The value which is going to be stored.
  745. *
  746. * @return {booolean} true if the new attribute value was stored, false if not.
  747. */
  748. _setAttrVal : function(attrName, subAttrName, prevVal, newVal) {
  749. var host = this,
  750. allowSet = true,
  751. state = host._state,
  752. validator = state.get(attrName, VALIDATOR),
  753. setter = state.get(attrName, SETTER),
  754. initializing = state.get(attrName, INITIALIZING),
  755. prevValRaw = this._getStateVal(attrName),
  756. name = subAttrName || attrName,
  757. retVal,
  758. valid;
  759. if (validator) {
  760. if (!validator.call) {
  761. // Assume string - trying to keep critical path tight, so avoiding Lang check
  762. validator = this[validator];
  763. }
  764. if (validator) {
  765. valid = validator.call(host, newVal, name);
  766. if (!valid && initializing) {
  767. newVal = state.get(attrName, DEF_VALUE);
  768. valid = true; // Assume it's valid, for perf.
  769. }
  770. }
  771. }
  772. if (!validator || valid) {
  773. if (setter) {
  774. if (!setter.call) {
  775. // Assume string - trying to keep critical path tight, so avoiding Lang check
  776. setter = this[setter];
  777. }
  778. if (setter) {
  779. retVal = setter.call(host, newVal, name);
  780. if (retVal === INVALID_VALUE) {
  781. Y.log('Attribute: ' + attrName + ', setter returned Attribute.INVALID_VALUE for value:' + newVal, 'warn', 'attribute');
  782. allowSet = false;
  783. } else if (retVal !== undefined){
  784. Y.log('Attribute: ' + attrName + ', raw value: ' + newVal + ' modified by setter to:' + retVal, 'info', 'attribute');
  785. newVal = retVal;
  786. }
  787. }
  788. }
  789. if (allowSet) {
  790. if(!subAttrName && (newVal === prevValRaw) && !Lang.isObject(newVal)) {
  791. Y.log('Attribute: ' + attrName + ', value unchanged:' + newVal, 'warn', 'attribute');
  792. allowSet = false;
  793. } else {
  794. // Store value
  795. if (state.get(attrName, INIT_VALUE) === undefined) {
  796. state.add(attrName, INIT_VALUE, newVal);
  797. }
  798. host._setStateVal(attrName, newVal);
  799. }
  800. }
  801. } else {
  802. Y.log('Attribute:' + attrName + ', Validation failed for value:' + newVal, 'warn', 'attribute');
  803. allowSet = false;
  804. }
  805. return allowSet;
  806. },
  807. /**
  808. * Sets multiple attribute values.
  809. *
  810. * @method setAttrs
  811. * @param {Object} attrs An object with attributes name/value pairs.
  812. * @return {Object} A reference to the host object.
  813. * @chainable
  814. */
  815. setAttrs : function(attrs, opts) {
  816. return this._setAttrs(attrs, opts);
  817. },
  818. /**
  819. * Implementation behind the public setAttrs method, to set multiple attribute values.
  820. *
  821. * @method _setAttrs
  822. * @protected
  823. * @param {Object} attrs An object with attributes name/value pairs.
  824. * @return {Object} A reference to the host object.
  825. * @chainable
  826. */
  827. _setAttrs : function(attrs, opts) {
  828. for (var attr in attrs) {
  829. if ( attrs.hasOwnProperty(attr) ) {
  830. this.set(attr, attrs[attr]);
  831. }
  832. }
  833. return this;
  834. },
  835. /**
  836. * Gets multiple attribute values.
  837. *
  838. * @method getAttrs
  839. * @param {Array | boolean} attrs Optional. An array of attribute names. If omitted, all attribute values are
  840. * returned. If set to true, all attributes modified from their initial values are returned.
  841. * @return {Object} An object with attribute name/value pairs.
  842. */
  843. getAttrs : function(attrs) {
  844. return this._getAttrs(attrs);
  845. },
  846. /**
  847. * Implementation behind the public getAttrs method, to get multiple attribute values.
  848. *
  849. * @method _getAttrs
  850. * @protected
  851. * @param {Array | boolean} attrs Optional. An array of attribute names. If omitted, all attribute values are
  852. * returned. If set to true, all attributes modified from their initial values are returned.
  853. * @return {Object} An object with attribute name/value pairs.
  854. */
  855. _getAttrs : function(attrs) {
  856. var host = this,
  857. o = {},
  858. i, l, attr, val,
  859. modifiedOnly = (attrs === true);
  860. attrs = (attrs && !modifiedOnly) ? attrs : O.keys(host._state.data.added);
  861. for (i = 0, l = attrs.length; i < l; i++) {
  862. // Go through get, to honor cloning/normalization
  863. attr = attrs[i];
  864. val = host.get(attr);
  865. if (!modifiedOnly || host._getStateVal(attr) != host._state.get(attr, INIT_VALUE)) {
  866. o[attr] = host.get(attr);
  867. }
  868. }
  869. return o;
  870. },
  871. /**
  872. * Configures a group of attributes, and sets initial values.
  873. *
  874. * <p>
  875. * <strong>NOTE:</strong> This method does not isolate the configuration object by merging/cloning.
  876. * The caller is responsible for merging/cloning the configuration object if required.
  877. * </p>
  878. *
  879. * @method addAttrs
  880. * @chainable
  881. *
  882. * @param {Object} cfgs An object with attribute name/configuration pairs.
  883. * @param {Object} values An object with attribute name/value pairs, defining the initial values to apply.
  884. * Values defined in the cfgs argument will be over-written by values in this argument unless defined as read only.
  885. * @param {boolean} lazy Whether or not to delay the intialization of these attributes until the first call to get/set.
  886. * Individual attributes can over-ride this behavior by defining a lazyAdd configuration property in their configuration.
  887. * See <a href="#method_addAttr">addAttr</a>.
  888. *
  889. * @return {Object} A reference to the host object.
  890. */
  891. addAttrs : function(cfgs, values, lazy) {
  892. var host = this; // help compression
  893. if (cfgs) {
  894. host._tCfgs = cfgs;
  895. host._tVals = host._normAttrVals(values);
  896. host._addAttrs(cfgs, host._tVals, lazy);
  897. host._tCfgs = host._tVals = null;
  898. }
  899. return host;
  900. },
  901. /**
  902. * Implementation behind the public addAttrs method.
  903. *
  904. * This method is invoked directly by get if it encounters a scenario
  905. * in which an attribute's valueFn attempts to obtain the
  906. * value an attribute in the same group of attributes, which has not yet
  907. * been added (on demand initialization).
  908. *
  909. * @method _addAttrs
  910. * @private
  911. * @param {Object} cfgs An object with attribute name/configuration pairs.
  912. * @param {Object} values An object with attribute name/value pairs, defining the initial values to apply.
  913. * Values defined in the cfgs argument will be over-written by values in this argument unless defined as read only.
  914. * @param {boolean} lazy Whether or not to delay the intialization of these attributes until the first call to get/set.
  915. * Individual attributes can over-ride this behavior by defining a lazyAdd configuration property in their configuration.
  916. * See <a href="#method_addAttr">addAttr</a>.
  917. */
  918. _addAttrs : function(cfgs, values, lazy) {
  919. var host = this, // help compression
  920. attr,
  921. attrCfg,
  922. value;
  923. for (attr in cfgs) {
  924. if (cfgs.hasOwnProperty(attr)) {
  925. // Not Merging. Caller is responsible for isolating configs
  926. attrCfg = cfgs[attr];
  927. attrCfg.defaultValue = attrCfg.value;
  928. // Handle simple, complex and user values, accounting for read-only
  929. value = host._getAttrInitVal(attr, attrCfg, host._tVals);
  930. if (value !== undefined) {
  931. attrCfg.value = value;
  932. }
  933. if (host._tCfgs[attr]) {
  934. delete host._tCfgs[attr];
  935. }
  936. host.addAttr(attr, attrCfg, lazy);
  937. }
  938. }
  939. },
  940. /**
  941. * Utility method to protect an attribute configuration
  942. * hash, by merging the entire object and the individual
  943. * attr config objects.
  944. *
  945. * @method _protectAttrs
  946. * @protected
  947. * @param {Object} attrs A hash of attribute to configuration object pairs.
  948. * @return {Object} A protected version of the attrs argument.
  949. */
  950. _protectAttrs : function(attrs) {
  951. if (attrs) {
  952. attrs = Y.merge(attrs);
  953. for (var attr in attrs) {
  954. if (attrs.hasOwnProperty(attr)) {
  955. attrs[attr] = Y.merge(attrs[attr]);
  956. }
  957. }
  958. }
  959. return attrs;
  960. },
  961. /**
  962. * Utility method to normalize attribute values. The base implementation
  963. * simply merges the hash to protect the original.
  964. *
  965. * @method _normAttrVals
  966. * @param {Object} valueHash An object with attribute name/value pairs
  967. *
  968. * @return {Object}
  969. *
  970. * @private
  971. */
  972. _normAttrVals : function(valueHash) {
  973. return (valueHash) ? Y.merge(valueHash) : null;
  974. },
  975. /**
  976. * Returns the initial value of the given attribute from
  977. * either the default configuration provided, or the
  978. * over-ridden value if it exists in the set of initValues
  979. * provided and the attribute is not read-only.
  980. *
  981. * @param {String} attr The name of the attribute
  982. * @param {Object} cfg The attribute configuration object
  983. * @param {Object} initValues The object with simple and complex attribute name/value pairs returned from _normAttrVals
  984. *
  985. * @return {Any} The initial value of the attribute.
  986. *
  987. * @method _getAttrInitVal
  988. * @private
  989. */
  990. _getAttrInitVal : function(attr, cfg, initValues) {
  991. var val, valFn;
  992. // init value is provided by the user if it exists, else, provided by the config
  993. if (!cfg[READ_ONLY] && initValues && initValues.hasOwnProperty(attr)) {
  994. val = initValues[attr];
  995. } else {
  996. val = cfg[VALUE];
  997. valFn = cfg[VALUE_FN];
  998. if (valFn) {
  999. if (!valFn.call) {
  1000. valFn = this[valFn];
  1001. }
  1002. if (valFn) {
  1003. val = valFn.call(this);
  1004. }
  1005. }
  1006. }
  1007. Y.log('initValue for ' + attr + ':' + val, 'info', 'attribute');
  1008. return val;
  1009. },
  1010. /**
  1011. * Returns an object with the configuration properties (and value)
  1012. * for the given attrubute. If attrName is not provided, returns the
  1013. * configuration properties for all attributes.
  1014. *
  1015. * @method _getAttrCfg
  1016. * @protected
  1017. * @param {String} name Optional. The attribute name. If not provided, the method will return the configuration for all attributes.
  1018. * @return {Object} The configuration properties for the given attribute, or all attributes.
  1019. */
  1020. _getAttrCfg : function(name) {
  1021. var o,
  1022. data = this._state.data;
  1023. if (data) {
  1024. o = {};
  1025. Y.each(data, function(cfg, cfgProp) {
  1026. if (name) {
  1027. if(name in cfg) {
  1028. o[cfgProp] = cfg[name];
  1029. }
  1030. } else {
  1031. Y.each(cfg, function(attrCfg, attr) {
  1032. o[attr] = o[attr] || {};
  1033. o[attr][cfgProp] = attrCfg;
  1034. });
  1035. }
  1036. });
  1037. }
  1038. return o;
  1039. },
  1040. /**
  1041. * Utility method to set up initial attributes defined during construction, either through the constructor.ATTRS property, or explicitly passed in.
  1042. *
  1043. * @method _initAttrs
  1044. * @protected
  1045. * @param attrs {Object} The attributes to add during construction (passed through to <a href="#method_addAttrs">addAttrs</a>). These can also be defined on the constructor being augmented with Attribute by defining the ATTRS property on the constructor.
  1046. * @param values {Object} The initial attribute values to apply (passed through to <a href="#method_addAttrs">addAttrs</a>). These are not merged/cloned. The caller is responsible for isolating user provided values if required.
  1047. * @param lazy {boolean} Whether or not to add attributes lazily (passed through to <a href="#method_addAttrs">addAttrs</a>).
  1048. */
  1049. _initAttrs : function(attrs, values, lazy) {
  1050. // ATTRS support for Node, which is not Base based
  1051. attrs = attrs || this.constructor.ATTRS;
  1052. var Base = Y.Base;
  1053. if ( attrs && !(Base && Y.instanceOf(this, Base))) {
  1054. this.addAttrs(this._protectAttrs(attrs), values, lazy);
  1055. }
  1056. }
  1057. };
  1058. // Basic prototype augment - no lazy constructor invocation.
  1059. Y.mix(Attribute, EventTarget, false, null, 1);
  1060. Y.Attribute = Attribute;
  1061. }, '3.4.1' ,{requires:['event-custom']});