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) {
95
return (d[key] && name in d[key]) ? d[key][name] : undefined;
99
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();
187
Y.log('att constructor called', 'info', 'attribute');
192
* Constants for clone formats supported by Attribute.
195
* By default attribute values returned by the get method
196
* are not cloned. However setting the attribute's "clone"
200
* <dt>Attribute.CLONE.DEEP</dt>
201
* <dd>Will result in a deep cloned value being returned
202
* (using YUI's clone method). This can be expensive for complex
205
* <dt>Attribute.CLONE.SHALLOW</dt>
206
* <dd>Will result in a shallow cloned value being returned
207
* (using YUI's merge method).
209
* <dt>Attribute.CLONE.IMMUTABLE</dt>
210
* <dd>Will result in a deep cloned value being returned
211
* when using the get method. Additionally users will
212
* not be able to set sub values of the attribute
213
* using the complex attribute notation (obj.set("x.y.z, 5)).
214
* However the value of the attribute can be changed, making
215
* it different from a READONLY attribute.
217
* <dt>Attribute.CLONE.NONE</dt>
219
* The value will not be cloned, resulting in a reference
220
* to the stored value being passed back, if the value is an object.
221
* This is the default behavior.
237
CLONE_ENUM = Attribute.CLONE;
239
Attribute.prototype = {
242
* Adds an attribute, with the provided configuration to the host object. Intended
243
* to be used by the host object to setup it's set of available attributes.
246
* The config argument object literal supports the following optional properties:
249
* <dt>value <Any></dt>
250
* <dd>The initial value to set on the attribute</dd>
251
* <dt>readOnly <Boolean></dt>
252
* <dd>Whether or not the attribute is read only. Attributes having readOnly set to true
253
* cannot be set by invoking the set method.</dd>
254
* <dt>writeOnce <Boolean></dt>
255
* <dd>Whether or not the attribute is "write once". Attributes having writeOnce set to true,
256
* can only have their values set once, be it through the default configuration,
257
* constructor configuration arguments, or by invoking set.</dd>
258
* <dt>set <Function></dt>
259
* <dd>The setter function to be invoked (within the context of the host object) before
260
* the attribute is stored by a call to the set method. The value returned by the
261
* set function will be the finally stored value.</dd>
262
* <dt>get <Function></dt>
263
* <dd>The getter function to be invoked (within the context of the host object) before
264
* the stored values is returned to a user invoking the get method for the attribute.
265
* The value returned by the get function is the final value which will be returned to the
266
* user when they invoke get.</dd>
267
* <dt>validator <Function></dt>
268
* <dd>The validator function which is invoked prior to setting the stored value. Returning
269
* false from the validator function will prevent the value from being stored</dd>
270
* <dt>clone <int></dt>
271
* <dd>If and how the value returned by a call to the get method, should be de-referenced from
272
* the stored value. By default values are not cloned, and hence a call to get will return
273
* a reference to the stored value. See Attribute.CLONE for more details about the clone
274
* options available</dd>
279
* @param {String} name The attribute key
280
* @param {Object} config (optional) An object literal specifying the configuration for the attribute.
281
* <strong>NOTE:</strong> The config object is modified when adding an attribute,
282
* so if you need to protect the original values, you will need to merge or clone the object.
285
addAtt: function(name, config) {
286
Y.log('adding attribute: ' + name, 'info', 'attribute');
287
var value, hasValue = (VALUE in config);
289
if (config[READ_ONLY] && !hasValue) { Y.log('readOnly attribute: ' + name + ', added without an initial value. Value will be set on intial call to set', 'warn', 'attribute');}
292
value = config.value;
296
this._conf.add(name, config);
299
this.set(name, value);
304
* Removes an attribute.
307
* @param {String} name The attribute key
309
removeAtt: function(name) {
310
this._conf.remove(name);
314
* Returns the current value of the attribute. If the attribute
315
* has been configured with a 'get' handler, this method will delegate
316
* to the 'get' handler to obtain the value of the attribute.
317
* The 'get' handler will be passed the current value of the attribute
318
* as the only argument.
322
* @param {String} key The attribute whose value will be returned. If
323
* the value of the attribute is an Object, dot notation can be used to
324
* obtain the value of a property of the object (e.g. <code>get("x.y.z")</code>)
326
* @return {Any} The current value of the attribute
328
get: function(name) {
330
var conf = this._conf,
336
if (name.indexOf(DOT) !== -1) {
337
path = name.split(DOT);
341
val = conf.get(name, VALUE);
342
getFn = conf.get(name, GET);
343
clone = conf.get(name, CLONE);
345
val = (clone) ? this._cloneAttVal(val, clone) : val;
346
val = (getFn) ? getFn.call(this, val) : val;
347
val = (path) ? this._getSubAttVal(path, val) : val;
353
* Sets the value of an attribute.
358
* @param {String} name The name of the attribute. Note, if the
359
* value of the attribute is an Object, dot notation can be used
360
* to set the value of a property within the object
361
* (e.g. <code>set("x.y.z", 5)</code>), if the attribute has not
362
* been declared as an immutable attribute (see <a href="#property_CLONE">Attribute.CLONE</a>).
364
* @param {Any} value The value to apply to the attribute
366
* @param {Object} opts Optional event data. This object will be mixed into
367
* the event facade passed as the first argument to subscribers
368
* of attribute change events
370
* @return {Object} Reference to the host object
372
set: function(name, val, opts) {
374
var conf = this._conf,
379
initialSet = (!data.value || !(name in data.value));
381
if (name.indexOf(DOT) !== -1) {
383
path = name.split(DOT);
387
if (path && conf.get(name, CLONE) === CLONE_ENUM.IMMUTABLE) {
388
Y.log('set ' + name + ' failed; Attribute is IMMUTABLE. Setting a sub value is not permitted', 'info', 'attribute');
393
if (conf.get(name, WRITE_ONCE)) {
394
Y.log('set ' + name + ' failed; Attribute is writeOnce', 'info', 'attribute');
397
if (conf.get(name, READ_ONLY)) {
398
Y.log('set ' + name + ' failed; Attribute is readOnly', 'info', 'attribute');
403
if (!conf.get(name)) {
404
Y.log('Set called with unconfigured attribute. Adding a new attribute: ' + name, 'info', 'attribute');
407
currVal = this.get(name);
410
val = this._setSubAttVal(path, Y.clone(currVal), val);
411
if (val === undefined) {
412
// Path not valid, don't set anything.
413
Y.log('set ' + strPath + 'failed; attribute sub path is invalid', 'error', 'attribute');
418
this._fireAttChange(name, currVal, val, name, strPath, opts);
425
* Alias for the Event.Target <a href="Event.Target.html#method_subscribe">subscribe</a> method.
428
* <p>Subscribers using this method to listen for attribute change events will be notified just
429
* <strong>before</strong> the state of the attribute has been modified, and before the default handler has been
432
* <p>The <a href="Event.Target.html#method_after">after</a> method, inherited from Event Target, can be used by subscribers
433
* who wish to be notified <strong>after</strong> the attribute's value has changed.</p>
435
* @param {String} type The event type. For attribute change events, the event type is "[Attribute Name]Change", e.g.
436
* for the attribute "enabled", the event type will be "enabledChange".
437
* @param {Function} fn The subscribed function to invoke
438
* @param {Object} context Optional execution context
439
* @param {Any*} args* 0..n additional arguments to append to supply to the subscribed function when the event fires.
441
* @return {Event.Handle} The handle object for unsubscribing the subscriber from the event.
444
return this.subscribe.apply(this, arguments);
448
* Default handler implementation for set events
452
* @param {Event.Facade} e The event object for the custom event
454
_defAttSet : function(e) {
455
var conf = this._conf,
459
valFn = conf.get(name, VALIDATOR),
460
setFn = conf.get(name, SET);
463
retVal = setFn.call(this, val);
464
if (retVal !== undefined) {
465
Y.log('attribute: ' + name + ' modified by setter', 'info', 'attribute');
466
val = retVal; // setter can change value
470
if (!valFn || valFn.call(this, val)) {
471
conf.add(name, { value: val });
472
e.newVal = conf.get(name, VALUE);
474
// Prevent "after" listeners from being
475
// invoked since nothing changed.
476
e.stopImmediatePropagation();
481
* Retrieves the sub value at the provided path,
482
* from the value object provided.
484
* @method _getSubAttVal
487
* @param {Array} path A path array, specifying the object traversal path
488
* from which to obtain the sub value.
489
* @param {Object} val The object from which to extract the property value
490
* @return {Any} The value stored in the path or undefined if not found.
492
_getSubAttVal: function (path, val) {
493
var pl = path.length,
497
for (i = 0; val !== undefined && i < pl; ++i) {
506
* Sets the sub value at the provided path on the value object.
507
* Returns the modified value object, or undefined if the path is invalid.
509
* @method _setSubAttVal
512
* @param {Array} path A path array, specifying the object traversal path
513
* at which to set the sub value.
514
* @param {Object} val The object on which to set the sub value.
515
* @param {Any} subval The sub value to set.
516
* @return {Object} The modified object, with the new sub value set, or
517
* undefined, if the path was invalid.
519
_setSubAttVal: function(path, val, subval) {
521
var leafIdx = path.length-1,
528
for (i = 0; o !== undefined && i < leafIdx; ++i) {
532
// Not preventing new properties from being added
533
if (o !== undefined /* && o[path[i]] !== undefined */) {
544
* Sets multiple attribute values.
547
* @param {Object} atts A hash of attributes: name/value pairs
549
setAtts: function(atts) {
550
for (var att in atts) {
551
if ( O.owns(atts, att) ) {
552
this.set(att, atts[att]);
558
* Gets multiple attribute values.
561
* @return {Object} A hash of attributes: name/value pairs
563
getAtts: function(atts) {
568
Y.each(this._conf.get(VALUE), function(val, att) {
576
* Configures attributes, and sets initial values
581
* @param {Object} cfg Attribute configuration object literal
582
* @param {Object} initValues Name/value hash of initial values to apply
584
_initAtts : function(cfg, initValues) {
592
values = this._splitAttVals(initValues);
595
if (O.owns(atts, att)) {
596
attCfg = Y.merge(atts[att]);
597
value = this._initAttVal(att, attCfg, values);
598
if (value !== undefined) {
599
attCfg.value = value;
601
this.addAtt(att, attCfg);
608
* Utility to split out regular attribute values
609
* from complex attribute values, so that complex
610
* attributes can be keyed by top level attribute name.
612
* @method _splitAttrValues
613
* @param {Object} valueHash Name/value hash of initial values
615
* @return {Object} Object literal with 2 properties - "simple" and "complex",
616
* containing simple and complex attribute values respectively keyed
617
* by attribute the top level attribute name.
620
_splitAttVals: function(valueHash) {
627
for (var k in valueHash) {
628
if (O.owns(valueHash, k)) {
629
if (k.indexOf(DOT) !== -1) {
632
v = subvals[attr] = subvals[attr] || [];
638
vals[k] = valueHash[k];
642
return { simple:vals, complex:subvals };
646
* Returns the initial value of the given attribute from
647
* either the default configuration provided, or the
648
* over-ridden value if it exists in the initValues
651
* @param {String} att Attribute name
652
* @param {Object} cfg Default attribute configuration
654
* @param {Object} initVales Initial attribute values, provided
657
* @return {Any} Initial value of the attribute.
659
* @method _initAttVal
662
_initAttVal : function(att, cfg, initValues) {
664
var hasVal = (VALUE in cfg),
674
if (!cfg[READ_ONLY] && initValues) {
676
simple = initValues.simple;
677
if (simple && O.owns(simple, att)) {
682
// Complex Attributes
683
complex = initValues.complex;
684
if (complex && O.owns(complex, att)) {
686
subvals = complex[att];
687
for (i = 0, l = subvals.length; i < l; ++i) {
688
path = subvals[i].path;
689
subval = subvals[i].value;
690
val = this._setSubAttVal(path, val, subval);
700
* Clone utility method, which will
701
* clone the provided value using YUI's
702
* merge, or clone utilities based
703
* on the clone type provided. See <a href="#property_CLONE">Attribute.CLONE</a>
706
* @method _cloneAttVal
708
* @param {Any} val Value to clone
709
* @param {int} type Clone type to use, See the CLONE property
710
* @return {Any} The cloned copy of the object, based on the provided type.
712
_cloneAttVal : function(val, type) {
714
case CLONE_ENUM.SHALLOW:
717
case CLONE_ENUM.DEEP:
718
case CLONE_ENUM.IMMUTABLE:
726
* Utility method to help setup the event payload and
727
* fire the attribute change event.
729
* @method _fireAttChange
731
* @param {String} type The event name
732
* @param {Any} currVal The current value of the attribute
733
* @param {Any} newVal The new value of the attribute
734
* @param {String} attrName The name of the attribute
735
* @param {String} strFullPath The full path of the property being changed,
736
* if this is a sub-attribute value being change
737
* @param {Function} defaultFn The default handler for the change event
738
* @param {Object} opts Any additional event data to mix into the attribute change event's event facade.
740
_fireAttChange: function(type, currVal, newVal, attrName, strFullPath, defaultFn, opts) {
741
type = type + CHANGE;
743
// TODO: Publishing temporarily, while we address event bubbling/queuing
744
this.publish(type, {queuable:false, defaultFn:this._defAttSet});
751
subAttrName: strFullPath
762
Y.mix(Attribute, Y.Event.Target, false, null, 1);
764
Y.Attribute = Attribute;
768
}, '3.0.0pr1' ,{requires:['event']});