Skip to content

Instantly share code, notes, and snippets.

@dazld
Forked from TimBeyer/_working-using-domains.md
Last active December 21, 2015 03:08
Show Gist options
  • Save dazld/6239656 to your computer and use it in GitHub Desktop.
Save dazld/6239656 to your computer and use it in GitHub Desktop.
Working with Domains

Working with 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.*`
// app.js
var express = require('express'),
domain = require('domain'),
createFactory = require('./factory'),
Layout = require('./layout'),
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 = createFactory();
requestDomain.factory = perRequestFactory; // put this onto the domain, so inside run, the factory is available
requestDomain.run(function () {
var view = new Layout();
var responseTime = Math.random() * 2500; // random response time
// Simulate async tasks
setTimeout(function () {
res.send(perRequestFactory.serializeModels());
}, responseTime);
});
});
app.listen(8000);
// 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 Backbone = require('backbone');
var SubView = require('./subview');
Backbone.$ = require('cheerio');
module.exports = Backbone.View.extend({
initialize: function () {
this.subView = new SubView();
this.$el.append(this.subView.$el);
},
render: function(){
this.subView.render();
this.$el.append(this.subView.$el);
}
});
var View = require('backbone').View;
module.exports = View.extend({
initialize: function () {
this.viewState = process.domain.factory.createModel({
collapsed: true,
hidden: false
});
},
render: function(){
this.$el.empty();
this.$el.html(this.viewState.toJSON());
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment