Skip to content

Instantly share code, notes, and snippets.

@TimBeyer
Last active December 21, 2015 03:08
Show Gist options
  • Save TimBeyer/6239589 to your computer and use it in GitHub Desktop.
Save TimBeyer/6239589 to your computer and use it in GitHub Desktop.

Working using domains

In this example we'd like to have a factory that works per request and allows to keep track of created Models We create a factory per request and create a domain to which we attach the factory That way the singleton is automatically shared with all parts of the application under process.domain.*

var express = require('express'),
domain = require('domain'),
factory = require('./factory'),
View = require('./view'),
app = express();
app.all('*', function(req, res, next) {
// We create a factory for every request and attach it to a new domain
// That way it is automatically available in all code executed in the context of this request
var requestDomain = domain.create();
var perRequestFactory = factory();
requestDomain.factory = perRequestFactory;
requestDomain.run(function () {
var view = new View({
collapsed: req.cookie.viewState.collapsed,
hidden: req.cookie.viewState.hidden
});
var responseTime = Math.random() * 2500; // random response time
// Simulate async tasks
setTimeout(function () {
res.send(perRequestFactory.serializeModels());
}, responseTime);
});
});
app.listen(8000);
// Basically a factory for factories
// For every request we create a new one
var Model = require('backbone').Model;
module.exports = function createFactory () {
var allModels = [];
return {
createModel: function (data) {
var model = new Model(data);
allModels.push(model);
return model;
},
serializeModels: function () {
return allModels.map(function (model) {
return model.toJSON();
});
},
reset: function () {
allModels = [];
}
}
};
var View = require('backbone').View;
module.exports = View.extend({
initialize: function (options) {
this.viewState = process.domain.factory.createModel({
collapsed: options.collapsed,
hidden: options.hidden
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment