Created
May 4, 2012 18:05
-
-
Save millermedeiros/2596657 to your computer and use it in GitHub Desktop.
"safe/strict" data store object
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
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. | |
} | |
} | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.