Skip to content

Instantly share code, notes, and snippets.

@millermedeiros
Created May 4, 2012 18:05
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save millermedeiros/2596657 to your computer and use it in GitHub Desktop.
Save millermedeiros/2596657 to your computer and use it in GitHub Desktop.
"safe/strict" data store object
define(function(){
//just so we can check against undefined and set val as undefined
var UNDEF;
// here you create the "interface", trying to get/set any other property
// will throw errors before build (see pragmas on get).
var _data = {
foo : UNDEF,
bar : UNDEF,
lorem : UNDEF,
ipsum : UNDEF
};
return {
get : function(id){
//>>includeStart("debug", pragmas.debug);
if (! (id in _data)) {
throw new Error('Invalid id: "'+ id +'"');
}
//>>includeEnd("debug")
return _data[ id ];
},
set : function(id, val){
var prevVal = this.get(id);
if (val !== prevVal) {
_data[ id ] = val;
// you could also dispatch an event here to tell the other
// modules the data has changed.
}
}
}
});
@millermedeiros
Copy link
Author

just to answer a RequireJS mailing list thread regarding using a centralized object to store app data.

I've been favoring a stricter structure to avoid typos and it also helps organization since I can dispatch events during changes. It will also help my code completion (since I set my editor to complete based on any word on any opened file).

I would also dispatch a changed signal or convert the returned object into a SignalEmitter (so it dispatches a different event for each property change). That way any object would be able to listen and react to changes.

PS: I've been using pragmas around code that is only required on development and r.js to remove it during build.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment