2
Copyright (c) 2008, Yahoo! Inc. All rights reserved.
3
Code licensed under the BSD License:
4
http://developer.yahoo.net/yui/license.txt
7
YUI.add('attribute', function(Y) {
10
* Managed Attribute Provider
15
* Maintain state for a collection of items. Individual properties
16
* are stored in hash tables. This is instead of having state objects
17
* for each item in the collection. For large collections, especially
18
* changing ones, this approach may perform better.
23
Y.State = function() {
35
* Add an item with all of the properties in the supplied object.
37
* @param name {string} identifier for this attribute
38
* @param o hash of attributes
40
add: function(name, o) {
41
Y.each(o, function(v, k) {
46
this.data[k][name] = v;
51
* Remove entire item, or optionally specified fields
53
* @param name {string} name of attribute
54
* @param o {string|object|array} single key or collection of keys to delete
56
remove: function(name, o) {
59
if (d[key] && (name in d[key])) {
64
if (Y.Lang.isString(o)) {
67
Y.each(o || d, function(v, k) {
68
if(Y.Lang.isString(k)) {
79
* For a given item, gets an attribute. If key is not
80
* supplied, a disposable object with all attributes is
81
* returned. Use of the latter option makes sense when
82
* working with single items, but not if object explosion
83
* might cause gc problems.
85
* @param name {string} name of attribute
86
* @param key {string} optional attribute to get
87
* @return either the value of the supplied key or an object with
90
// get: function(name, key, val) {
91
get: function(name, key) {
96
return (d[key] && name in d[key]) ? d[key][name] : undefined;
98
Y.each(d, function(v, k) {
110
// figure out what kind of functionality we may need here
112
// get a list of items and values for a given key
113
// get a list of items where a key has the supplied value
115
list: function(key, val) {
116
var o = {}, d = this.data, test = !L.isUndefined(val);
118
Y.each(this, function(v, k) {
121
if (key && k !== key) {
123
// verify value. note, v will be the item names, so this
124
// isn't working ... need to iterate v items
125
} else if (test && v !== val) {
139
* Managed Attribute Provider
151
READ_ONLY = "readOnly",
152
WRITE_ONCE = "writeOnce",
153
VALIDATOR = "validator",
159
* Attribute provides managed attribute support.
162
* The class is designed to be augmented onto a host class,
163
* and allows the host to support get/set methods for attributes,
164
* initial configuration support and attribute change events.
166
* <p>Attributes added to the host can:</p>
168
* <li>Be defined as read-only.</li>
169
* <li>Be defined as write-once.</li>
170
* <li>Be defined with a set function, used to manipulate
171
* values passed to Attribute's set method, before they are stored.</li>
172
* <li>Be defined with a validator function, to validate values before they are stored.</li>
173
* <li>Be defined with a get function, which can be used to manipulate stored values,
174
* before they are returned by Attribute's get method.</li>
175
* <li>Specify if and how they should be cloned on 'get' (see <a href="#property_CLONE">Attribute.CLONE</a> for supported clone modes).</li>
178
* <p>See the <a href="#method_addAtt">addAtt</a> method, for details about how to add attributes with
179
* a specific configuration</p>
184
function Attribute() {
185
Y.Event.Target.call(this, {emitFacade:true});
186
this._conf = this._conf || new Y.State();
191
* Constants for clone formats supported by Attribute.
194
* By default attribute values returned by the get method
195
* are not cloned. However setting the attribute's "clone"
199
* <dt>Attribute.CLONE.DEEP</dt>
200
* <dd>Will result in a deep cloned value being returned
201
* (using YUI's clone method). This can be expensive for complex
204
* <dt>Attribute.CLONE.SHALLOW</dt>
205
* <dd>Will result in a shallow cloned value being returned
206
* (using YUI's merge method).
208
* <dt>Attribute.CLONE.IMMUTABLE</dt>
209
* <dd>Will result in a deep cloned value being returned
210
* when using the get method. Additionally users will
211
* not be able to set sub values of the attribute
212
* using the complex attribute notation (obj.set("x.y.z, 5)).
213
* However the value of the attribute can be changed, making
214
* it different from a READONLY attribute.
216
* <dt>Attribute.CLONE.NONE</dt>
218
* The value will not be cloned, resulting in a reference
219
* to the stored value being passed back, if the value is an object.
220
* This is the default behavior.
236
CLONE_ENUM = Attribute.CLONE;
238
Attribute.prototype = {
241
* Adds an attribute, with the provided configuration to the host object. Intended
242
* to be used by the host object to setup it's set of available attributes.
245
* The config argument object literal supports the following optional properties:
248
* <dt>value <Any></dt>
249
* <dd>The initial value to set on the attribute</dd>
250
* <dt>readOnly <Boolean></dt>
251
* <dd>Whether or not the attribute is read only. Attributes having readOnly set to true
252
* cannot be set by invoking the set method.</dd>
253
* <dt>writeOnce <Boolean></dt>
254
* <dd>Whether or not the attribute is "write once". Attributes having writeOnce set to true,
255
* can only have their values set once, be it through the default configuration,
256
* constructor configuration arguments, or by invoking set.</dd>
257
* <dt>set <Function></dt>
258
* <dd>The setter function to be invoked (within the context of the host object) before
259
* the attribute is stored by a call to the set method. The value returned by the
260
* set function will be the finally stored value.</dd>
261
* <dt>get <Function></dt>
262
* <dd>The getter function to be invoked (within the context of the host object) before
263
* the stored values is returned to a user invoking the get method for the attribute.
264
* The value returned by the get function is the final value which will be returned to the
265
* user when they invoke get.</dd>
266
* <dt>validator <Function></dt>
267
* <dd>The validator function which is invoked prior to setting the stored value. Returning
268
* false from the validator function will prevent the value from being stored</dd>
269
* <dt>clone <int></dt>
270
* <dd>If and how the value returned by a call to the get method, should be de-referenced from
271
* the stored value. By default values are not cloned, and hence a call to get will return
272
* a reference to the stored value. See Attribute.CLONE for more details about the clone
273
* options available</dd>
278
* @param {String} name The attribute key
279
* @param {Object} config (optional) An object literal specifying the configuration for the attribute.
280
* <strong>NOTE:</strong> The config object is modified when adding an attribute,
281
* so if you need to protect the original values, you will need to merge or clone the object.
284
addAtt: function(name, config) {
285
var value, hasValue = (VALUE in config);
289
value = config.value;
293
config.initValue = value;
294
this._conf.add(name, config);
297
this.set(name, value);
302
* Resets the given attribute or all attributes to the initial value.
305
* @param {String} name optional An attribute to reset. If omitted, all attributes are reset
307
reset: function(name) {
309
this.set(name, this._conf.data['initValue'][name]);
311
var initVals = this._conf.data['initValue'];
312
Y.each(initVals, function(v, n) {
319
* Removes an attribute.
322
* @param {String} name The attribute key
324
removeAtt: function(name) {
325
this._conf.remove(name);
329
* Returns the current value of the attribute. If the attribute
330
* has been configured with a 'get' handler, this method will delegate
331
* to the 'get' handler to obtain the value of the attribute.
332
* The 'get' handler will be passed the current value of the attribute
333
* as the only argument.
337
* @param {String} key The attribute whose value will be returned. If
338
* the value of the attribute is an Object, dot notation can be used to
339
* obtain the value of a property of the object (e.g. <code>get("x.y.z")</code>)
341
* @return {Any} The current value of the attribute
343
get: function(name) {
345
var conf = this._conf,
351
if (name.indexOf(DOT) !== -1) {
352
path = name.split(DOT);
356
val = conf.get(name, VALUE);
357
getFn = conf.get(name, GET);
358
clone = conf.get(name, CLONE);
360
val = (clone) ? this._cloneAttVal(val, clone) : val;
361
val = (getFn) ? getFn.call(this, val) : val;
362
val = (path) ? this._getSubAttVal(path, val) : val;
368
* Allows setting of readOnly/writeOnce attributes.
373
* @return {Object} Reference to the host object
375
_set: function(name, val, opts) {
376
return this.set(name, val, opts, true);
380
* Sets the value of an attribute.
385
* @param {String} name The name of the attribute. Note, if the
386
* value of the attribute is an Object, dot notation can be used
387
* to set the value of a property within the object
388
* (e.g. <code>set("x.y.z", 5)</code>), if the attribute has not
389
* been declared as an immutable attribute (see <a href="#property_CLONE">Attribute.CLONE</a>).
391
* @param {Any} value The value to apply to the attribute
393
* @param {Object} opts Optional event data. This object will be mixed into
394
* the event facade passed as the first argument to subscribers
395
* of attribute change events
397
* @return {Object} Reference to the host object
399
set: function(name, val, opts, privateSet) {
400
var conf = this._conf,
405
initialSet = (!data.value || !(name in data.value));
407
if (name.indexOf(DOT) !== -1) {
409
path = name.split(DOT);
413
if (path && conf.get(name, CLONE) === CLONE_ENUM.IMMUTABLE) {
417
if (!initialSet && !privateSet) {
418
if (conf.get(name, WRITE_ONCE)) {
421
if (conf.get(name, READ_ONLY)) {
426
if (!conf.get(name)) {
430
currVal = this.get(name);
433
val = this._setSubAttVal(path, Y.clone(currVal), val);
434
if (val === undefined) {
435
// Path not valid, don't set anything.
440
this._fireAttChange(name, currVal, val, name, strPath, opts);
447
* Alias for the Event.Target <a href="Event.Target.html#method_subscribe">subscribe</a> method.
450
* <p>Subscribers using this method to listen for attribute change events will be notified just
451
* <strong>before</strong> the state of the attribute has been modified, and before the default handler has been
454
* <p>The <a href="Event.Target.html#method_after">after</a> method, inherited from Event Target, can be used by subscribers
455
* who wish to be notified <strong>after</strong> the attribute's value has changed.</p>
457
* @param {String} type The event type. For attribute change events, the event type is "[Attribute Name]Change", e.g.
458
* for the attribute "enabled", the event type will be "enabledChange".
459
* @param {Function} fn The subscribed function to invoke
460
* @param {Object} context Optional execution context
461
* @param {Any*} args* 0..n additional arguments to append to supply to the subscribed function when the event fires.
463
* @return {Event.Handle} The handle object for unsubscribing the subscriber from the event.
466
return this.subscribe.apply(this, arguments);
470
* Default handler implementation for set events
474
* @param {Event.Facade} e The event object for the custom event
476
_defAttSet : function(e) {
477
var conf = this._conf,
481
valFn = conf.get(name, VALIDATOR),
482
setFn = conf.get(name, SET);
485
retVal = setFn.call(this, val);
486
if (retVal !== undefined) {
487
val = retVal; // setter can change value
491
if (!valFn || valFn.call(this, val)) {
492
conf.add(name, { value: val });
493
e.newVal = conf.get(name, VALUE);
495
// Prevent "after" listeners from being
496
// invoked since nothing changed.
497
e.stopImmediatePropagation();
502
* Retrieves the sub value at the provided path,
503
* from the value object provided.
505
* @method _getSubAttVal
508
* @param {Array} path A path array, specifying the object traversal path
509
* from which to obtain the sub value.
510
* @param {Object} val The object from which to extract the property value
511
* @return {Any} The value stored in the path or undefined if not found.
513
_getSubAttVal: function (path, val) {
514
var pl = path.length,
518
for (i = 0; val !== undefined && i < pl; ++i) {
527
* Sets the sub value at the provided path on the value object.
528
* Returns the modified value object, or undefined if the path is invalid.
530
* @method _setSubAttVal
533
* @param {Array} path A path array, specifying the object traversal path
534
* at which to set the sub value.
535
* @param {Object} val The object on which to set the sub value.
536
* @param {Any} subval The sub value to set.
537
* @return {Object} The modified object, with the new sub value set, or
538
* undefined, if the path was invalid.
540
_setSubAttVal: function(path, val, subval) {
542
var leafIdx = path.length-1,
549
for (i = 0; o !== undefined && i < leafIdx; ++i) {
553
// Not preventing new properties from being added
554
if (o !== undefined /* && o[path[i]] !== undefined */) {
565
* Sets multiple attribute values.
568
* @param {Object} atts A hash of attributes: name/value pairs
570
setAtts: function(atts) {
571
for (var att in atts) {
572
if ( O.owns(atts, att) ) {
573
this.set(att, atts[att]);
579
* Gets multiple attribute values.
582
* @param {Array} Optional. An array of attribute names, whose values are required. If omitted, all attribute values are
584
* @return {Object} A hash of attributes: name/value pairs
586
getAtts: function(atts) {
587
var o = {}, i, l, att;
588
atts = atts || O.keys(this._conf.data[VALUE]);
590
for (i = 0, l = atts.length; i < l; i++) {
591
// Go through get, to retrieve massaged values and honor cloning
593
o[att] = this.get(att);
600
* Configures attributes, and sets initial values
605
* @param {Object} cfg Attribute configuration object literal
606
* @param {Object} initValues Name/value hash of initial values to apply
608
_initAtts : function(cfg, initValues) {
616
values = this._splitAttVals(initValues);
619
if (O.owns(atts, att)) {
620
attCfg = Y.merge(atts[att]);
621
value = this._initAttVal(att, attCfg, values);
622
if (value !== undefined) {
623
attCfg.value = value;
626
this.addAtt(att, attCfg);
633
* Utility to split out regular attribute values
634
* from complex attribute values, so that complex
635
* attributes can be keyed by top level attribute name.
637
* @method _splitAttrValues
638
* @param {Object} valueHash Name/value hash of initial values
640
* @return {Object} Object literal with 2 properties - "simple" and "complex",
641
* containing simple and complex attribute values respectively keyed
642
* by attribute the top level attribute name.
645
_splitAttVals: function(valueHash) {
652
for (var k in valueHash) {
653
if (O.owns(valueHash, k)) {
654
if (k.indexOf(DOT) !== -1) {
657
v = subvals[attr] = subvals[attr] || [];
663
vals[k] = valueHash[k];
667
return { simple:vals, complex:subvals };
671
* Returns the initial value of the given attribute from
672
* either the default configuration provided, or the
673
* over-ridden value if it exists in the initValues
676
* @param {String} att Attribute name
677
* @param {Object} cfg Default attribute configuration
679
* @param {Object} initVales Initial attribute values, provided
682
* @return {Any} Initial value of the attribute.
684
* @method _initAttVal
687
_initAttVal : function(att, cfg, initValues) {
689
var hasVal = (VALUE in cfg),
690
val = (cfg.valueFn) ? cfg.valueFn.call(this) : cfg.value,
699
if (!cfg[READ_ONLY] && initValues) {
701
simple = initValues.simple;
702
if (simple && O.owns(simple, att)) {
707
// Complex Attributes
708
complex = initValues.complex;
709
if (complex && O.owns(complex, att)) {
711
subvals = complex[att];
712
for (i = 0, l = subvals.length; i < l; ++i) {
713
path = subvals[i].path;
714
subval = subvals[i].value;
715
val = this._setSubAttVal(path, val, subval);
725
* Clone utility method, which will
726
* clone the provided value using YUI's
727
* merge, or clone utilities based
728
* on the clone type provided. See <a href="#property_CLONE">Attribute.CLONE</a>
731
* @method _cloneAttVal
733
* @param {Any} val Value to clone
734
* @param {int} type Clone type to use, See the CLONE property
735
* @return {Any} The cloned copy of the object, based on the provided type.
737
_cloneAttVal : function(val, type) {
739
case CLONE_ENUM.SHALLOW:
742
case CLONE_ENUM.DEEP:
743
case CLONE_ENUM.IMMUTABLE:
751
* Utility method to help setup the event payload and
752
* fire the attribute change event.
754
* @method _fireAttChange
756
* @param {String} type The event name
757
* @param {Any} currVal The current value of the attribute
758
* @param {Any} newVal The new value of the attribute
759
* @param {String} attrName The name of the attribute
760
* @param {String} strFullPath The full path of the property being changed,
761
* if this is a sub-attribute value being change
762
* @param {Object} opts Any additional event data to mix into the attribute change event's event facade.
764
_fireAttChange: function(type, currVal, newVal, attrName, strFullPath, opts) {
765
type = type + CHANGE;
767
// TODO: Publishing temporarily, while we address event bubbling/queuing
768
this.publish(type, {queuable:false, defaultFn:this._defAttSet, silent:true});
775
subAttrName: strFullPath
786
Y.mix(Attribute, Y.Event.Target, false, null, 1);
788
Y.Attribute = Attribute;
792
}, '3.0.0pr2' ,{requires:['event']});