State.js revision 698543a874206e0c411b376e0c2892233a6a8fef
394N/A /**
394N/A * Managed Attribute Provider
394N/A * @module attribute
394N/A */
394N/A
394N/A /**
394N/A * Maintain state for a collection of items. Individual properties
394N/A * are stored in hash tables. This is instead of having state objects
394N/A * for each item in the collection. For large collections, especially
394N/A * changing ones, this approach may perform better.
394N/A *
394N/A * @constructor
394N/A * @class State
394N/A */
394N/A Y.State = function() {
394N/A /**
394N/A * Hash of attributes
394N/A * @property data
394N/A */
394N/A this.data = {};
3817N/A };
394N/A
394N/A Y.State.prototype = {
394N/A
394N/A /**
394N/A * Add an item with all of the properties in the supplied object.
394N/A * @method add
394N/A * @param name {string} identifier for this attribute
394N/A * @param o hash of attributes
394N/A */
618N/A addAll: function(name, o) {
394N/A var key;
394N/A for (key in o) {
844N/A if (o.hasOwnProperty(key)) {
844N/A this.add(name, key, o[key]);
394N/A }
1258N/A }
394N/A },
2899N/A
2899N/A /**
2818N/A * Add an item with the property and value provided
2818N/A * @method add
2818N/A * @param name {string} identifier for this attribute
3817N/A * @param key {string} property identifier
3817N/A * @param val {Any} property value
3817N/A */
394N/A add : function(name, key, val) {
783N/A var d = this.data;
783N/A d[key] = d[key] || {};
783N/A d[key][name] = val;
1938N/A },
1938N/A
394N/A /**
1716N/A * Remove entire item, or optionally specified fields
394N/A * @method remove
1716N/A * @param name {string} name of attribute
394N/A * @param o {string|object|array} single key or collection of keys to delete
394N/A */
394N/A remove: function(name, o) {
4337N/A var d = this.data,
4337N/A del = function(key) {
if (d[key] && (name in d[key])) {
delete d[key][name];
}
};
if (Y.Lang.isString(o)) {
del(o);
} else {
Y.each(o || d, function(v, k) {
if(Y.Lang.isString(k)) {
del(k);
} else {
del(v);
}
}, this);
}
},
/**
* For a given item, gets an attribute. If key is not
* supplied, a disposable object with all attributes is
* returned. Use of the latter option makes sense when
* working with single items, but not if object explosion
* might cause gc problems.
* @method get
* @param name {string} name of attribute
* @param key {string} optional attribute to get
* @return either the value of the supplied key or an object with
* all data.
*/
get: function(name, key) {
var d = this.data;
return (d[key] && name in d[key]) ? d[key][name] : undefined;
},
getAll : function(name) {
var d = this.data, o;
Y.each(d, function(v, k) {
if (name in d[k]) {
o = o || {};
o[k] = v[name];
}
}, this);
return o;
}
};