/**
* The State class maintains state for a collection of named items, with
* a varying number of properties defined.
*
* It avoids the need to create a separate class for the item, and separate instances
* of these classes for each item, by storing the state in a 2 level hash table,
* improving performance when the number of items is likely to be large.
*
* @constructor
* @class State
*/
Y.State = function() {
/**
* Hash of attributes
* @property data
*/
this.data = {};
};
Y.State.prototype = {
/**
* Adds a property to an item.
*
* @method add
* @param name {String} The name of the item.
* @param key {String} The name of the property.
* @param val {Any} The value of the property.
*/
add : function(name, key, val) {
var d = this.data;
d[key] = d[key] || {};
d[key][name] = val;
},
/**
* Adds multiple properties to an item.
*
* @method addAll
* @param name {String} The name of the item.
* @param o {Object} A hash of property/value pairs.
*/
addAll: function(name, o) {
var key;
for (key in o) {
if (o.hasOwnProperty(key)) {
this.add(name, key, o[key]);
}
}
},
/**
* Removes a property from an item.
*
* @method remove
* @param name {String} The name of the item.
* @param key {String} The property to remove.
*/
remove: function(name, key) {
var d = this.data;
if (d[key] && (name in d[key])) {
delete d[key][name];
}
},
/**
* Removes multiple properties from an item, or remove the item completely.
*
* @method removeAll
* @param name {String} The name of the item.
* @param o {Object|Array} Collection of properties to delete. If not provided, the entire item is removed.
*/
removeAll: function(name, o) {
var d = this.data;
Y.each(o || d, function(v, k) {
if(Y.Lang.isString(k)) {
this.remove(name, k);
} else {
this.remove(name, v);
}
}, this);
},
/**
* For a given item, returns the value of the property requested, or undefined if not found.
*
* @method get
* @param name {String} The name of the item
* @param key {String} Optional. The property value to retrieve.
* @return {Any} The value of the supplied property.
*/
get: function(name, key) {
var d = this.data;
return (d[key] && name in d[key]) ? d[key][name] : undefined;
},
/**
* For the given item, returns a disposable object with all of the
* item's property/value pairs.
*
* @method getAll
* @param name {String} The name of the item
* @return {Object} An object with property/value pairs for the item.
*/
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;
}
};