State.js revision fdaf522f78615dc3145b1771f6f8daba2df06bb6
/**
* 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[name] = d[name] || {};
d[name][key] = 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[name]) {
delete d[name][key];
}
},
/**
* 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[name]) ? d[name][key] : undefined;
},
/**
* For the given item, returns an object with all of the
* item's property/value pairs. By default the object returned
* is a shallow copy of the stored data, but passing in true
* as the second parameter will return a reference to the stored
* data.
*
* @method getAll
* @param name {String} The name of the item
* @param reference {boolean} true, if you want a reference to the stored
* object
* @return {Object} An object with property/value pairs for the item.
*/
getAll : function(name, reference) {
var d = this.data, o;
if (!reference) {
Y.each(d[name], function(v, k) {
o = o || {};
o[k] = v;
});
} else {
o = d[name];
}
return o;
}
};