Skip to content

Instantly share code, notes, and snippets.

@appsforartists
Created October 1, 2014 20:29
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 appsforartists/7b6e78e84ddddbe0ecf3 to your computer and use it in GitHub Desktop.
Save appsforartists/7b6e78e84ddddbe0ecf3 to your computer and use it in GitHub Desktop.
Prototyping context local storage in JavaScript
/* Problem:
* Building an isomorphic app with Webpack makes it hard to share dynamic
* data between the client and server. If you're running multiple apps in
* parallel, you can't use globals because they'll collide. You could
* probably come up with something that involves caching them to the
* filesystem and requiring it from the right places, but serializing
* dynamic data to the filesystem is gross.
*
* This is a proof of concept demonstrates two instances of View, each with
* their own parallel instance of settings, thanks to some call stack
* sorcery. */
function View () {
console.log(
getFromSettings('fruit')
);
};
var viewFactory = function () {
// instantiate the view here
return new View();
};
// wrap the views in a closure to hold the data
var wrapperA = getWrapper(viewFactory);
var wrapperB = getWrapper(viewFactory);
// put the data on the closure
wrapperA.settings = {
"fruit": "banana"
};
wrapperB.settings = {
"fruit": "mango"
};
// start the factories, which creates the views, and traces out the results
wrapperA();
wrapperB();
function getFromSettings (key) {
var backup = Error.prepareStackTrace;
var settings;
Error.prepareStackTrace = function (error, stack) {
settings = stack[0].getFunction().settings;
};
var error = new Error();
Error.captureStackTrace(error, StackTap);
error.stack;
Error.prepareStackTrace = backup;
return settings[key];
}
function getWrapper (callback) {
return function () {
StackTap(callback);
};
};
function StackTap (callback) {
callback();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment