Created
January 5, 2012 19:12
-
-
Save wemakeweb/1566716 to your computer and use it in GitHub Desktop.
key shared values store
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module.exports = (function (o) { | |
//the actual object | |
var cache = {}; | |
function Filehandler (o) { | |
if (!o.deleter || !o.loader) { | |
throw new Error("Delete or Load callback was not passed"); | |
} | |
this.loader = o.loader; | |
this.deleter = o.deleter; | |
if (o.onchange) { | |
this.onchange = o.onchange; | |
} else { | |
this.onchange = function () {}; | |
} | |
}; | |
Filehandler.prototype.setStatic = function (arr) { | |
this.setDynamic('static', arr); | |
}; | |
Filehandler.prototype.setDynamic = function (key, arr) { | |
var toLoad = [], | |
toDelete = []; | |
//remove file for that key | |
$.each(cache, function (i, files) { | |
var id = files.indexOf(key); | |
if (id != -1) files.splice(id, 1); | |
}); | |
//insert the new ones | |
$.each(arr, function (i, file) { | |
if (file in cache) { | |
cache[file].push(key); | |
} else { | |
toLoad.push(file); | |
cache[file] = [key]; | |
} | |
}); | |
toDelete = collectDeletes.call(this); | |
if (toLoad.length > 0) { | |
this.loader.call(this.loader, toLoad); | |
} | |
if (toDelete.length > 0) { | |
this.deleter.call(this.deleter, toDelete); | |
} | |
if (toDelete.length > 0 || toLoad.length > 0) { | |
this.onchange.call(this.onchange); | |
} | |
} | |
function collectDeletes() { | |
var toDelete = []; | |
$.each(cache, function (file, ids) { | |
if (ids.length === 0) { | |
toDelete.push(file); | |
delete cache[file]; | |
} | |
}); | |
return toDelete; | |
} | |
return new Filehandler(o); | |
}); | |
var Filehandler = require('Filehandler'); | |
//Usage | |
var handler = Filehandler({ | |
loader: function (files) { | |
console.log('load', files); | |
}, | |
deleter: function (files) { | |
console.log('delete', files) | |
}, | |
onchange: function () { | |
} | |
}); | |
var handler2 = Filehandler({ | |
loader: function (files) { | |
console.log('load2', files); | |
}, | |
deleter: function (files) { | |
console.log('delete2', files) | |
} | |
}); | |
handler.setDynamic('banane', [3, 4, 5, 6]); | |
handler.setStatic([8, 9, 10]); | |
handler.setStatic([9]); | |
handler.setDynamic('apfel', [3, 6, 7, 8]); | |
handler.setDynamic('banane', [2]); | |
handler2.setDynamic('üftz', [1, 2, 3, 4, 5, 6, 7, 8, 9]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment