Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@evitolins
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save evitolins/57b13ba8cff544b5d97e to your computer and use it in GitHub Desktop.
Save evitolins/57b13ba8cff544b5d97e to your computer and use it in GitHub Desktop.
A simple class to manipulate key/value data, and execute a defined array callbacks.
var DataModel = function () { "use strict";
var data = {},
callbacks = {
'set' : [],
'unset' : []
},
applyCallbacks = function (action, args) {
var cb, len, i;
if (callbacks[action] === undefined) return;
len = callbacks[action].length;
for (i=0; i < len; i++) {
cb = callbacks[action][i];
if (typeof cb === 'function') {
cb.apply(undefined, args);
}
}
};
return {
appendCallback : function (action, callback) {
if (callbacks[action] !== undefined) {
callbacks[action].push(callback);
}
},
removeCallback : function (action, callback) {
var cb, len, i;
if (callbacks[action] === undefined) return;
len = callbacks[action].length;
for (i=0; i < len; i++) {
cb = callbacks[action][i];
if (cb === callback) {
callbacks[action].splice(i, 1);
}
}
},
set : function (key, value) {
data[key] = value;
applyCallbacks('set', [key, value]);
},
unset : function (key) {
if (data[key] !== undefined) {
delete data[key];
applyCallbacks('unset', [key]);
}
},
get : function (key) {
return data[key];
},
getAll : function () {
return data;
}
};
};
var data = new DataModel()
callbackA = function (key, value) {
console.log('callbackA: ' + key + ' => ' + value);
},
callbackB = function (key, value) {
console.log('callbackB: ' + key + ' => ' + value);
},
callbackC = function (key, value) {
console.log('callbackC: ' + key + ' => ' + value);
};
data.appendCallback('set', callbackA);
data.appendCallback('set', callbackB);
data.appendCallback('set', callbackC);
data.appendCallback('unset', function (key, value) {
console.log('unset: ' + key + ' => ' + value);
});
data.set(12, "original text");
data.set(12, "new text");
data.removeCallback('set', cbB);
data.set(42, "forty two");
data.set(76, "seventy six");
data.set(123, "one hundred twenty three");
data.unset(76);
data.set("abc", "alphabeta")
console.log(data.getAll());
console.log(data.get(42));
console.log(data.get(234));
console.log(data.get("abc"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment