Previous question:
The idea is to have some storage interface that exists of different buckets - known as Eagle
s:
Eagle('bucket1');
Eagle('bucket2');
Every Eagle
data is stored as Feather
s.
var e = Eagle('fooEagle');
e.set('myFeather',{
'foo' : 'bar';
});
These Feather
s can be observed for changes (nothing more at this moment):
var f = e.get('myFeather');
f.on('change',function(f, key) {
console.log(key+ ' index of the Feather was changed to'+ f.get(key)));
});
f.set('foo','newer foo');
You could also retrieve data in a long chain like this:
Eagle('fooEagle').get('myFeather').get('foo');
Does this seem like a good approach? If so, how would you implement events like 'delete'. And would it be useful to let those events bubble up to the Eagle
? If so, how?
window.Eagle = (function(){
"use strict";
var _eagleInstances = [],
_featherInstances = [];
var Feather = (function() {
var _data = {},
_observers = {};
var F = function(data) {
this._id = _featherInstances.length;
_featherInstances[this._id] = this;
_data[this._id] = data;
}
F.prototype.has = function(key) {
return _data[this._id].hasOwnProperty(key);
}
F.prototype.get = function(key) {
return this.has(key) ? _data[this._id][key] : undefined;
}
F.prototype.set = function(key, data) {
_data[this._id][key] = data;
this.notify('change', key);
return this;
}
F.prototype.on = function(action, callable) {
if ( ! _observers.hasOwnProperty(action) ) {
_observers[action] = [];
}
_observers[action].push(callable);
}
F.prototype.notify = function(action, info) {
if ( _observers.hasOwnProperty(action) ) {
for ( var i = 0; i < _observers[action].length; i++ ) {
_observers[action][i](this, info);
}
}
}
return F;
})();
var Eagle = (function(){
var _feathers = {};
var E = function() {
this._id = _eagleInstances.length;
_feathers[this._id] = {};
_eagleInstances[this._id] = this;
}
E.prototype.has = function(featherIdentifier) {
return _feathers[this._id].hasOwnProperty(featherIdentifier);
}
E.prototype.get = function(featherIdentifier) {
if ( !this.has(featherIdentifier) ) {
this.set(featherIdentifier, {});
}
return _featherInstances[_feathers[this._id][featherIdentifier]];
}
E.prototype.set = function(featherIdentifier, data) {
var f = new Feather(data);
_feathers[this._id][featherIdentifier] = f._id;
return f;
}
return E;
})();
return function(eagleIdentifier) {
if ( !_eagleInstances.hasOwnProperty(eagleIdentifier) ) {
_eagleInstances[eagleIdentifier] = new Eagle();
}
return _eagleInstances[eagleIdentifier];
}
})();