Skip to content

Instantly share code, notes, and snippets.

@TimBeyer
Forked from dazld/broken_app.js
Last active December 21, 2015 01:49
Show Gist options
  • Save TimBeyer/6230802 to your computer and use it in GitHub Desktop.
Save TimBeyer/6230802 to your computer and use it in GitHub Desktop.
// In this example we'd like to have a factory that works per request and allows to keep track of created Models
// The singleton will however apply to all requests and thus keep growing
// For that reason we supply it with a reset function.
// This works fine until between receiving a request and sending a response there is no asynchronous code execution
// Once multiple requests come in in very short intervals, the asynchronous execution will lead to requests cross-polluting
// the singleton class
// factory.js
//
// Should be per-request so we can keep track
// of all models that were instantiated during the request lifetime
var Model = require('backbone').Model;
var allModels = [];
module.exports = {
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 = [];
}
};
// view.js
var Factory = require('./factory');
var View = require('backbone').View;
return View.extend({
initialize: function () {
this.viewState = Factory.createModel({
collapsed: true,
hidden: false
});
}
});
// app.js
var express = require('express'),
app = express(),
factory = require('./factory'),
View = require('./view');
app.all('*', function(req, res, next) {
var view = new View();
var responseTime = Math.random() * 2500; // random response time
// Simulate async tasks
setTimeout(function () {
res.send(factory.serializeModels());
factory.reset();
}, responseTime);
});
app.listen(8000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment