Skip to content

Instantly share code, notes, and snippets.

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

Working but complicated

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 pass it around to the parts of the code that need access This can quickly lead to hard to understand, messy code

var express = require('express'),
app = express(),
factory = require('./factory'),
View = require('./view');
app.all('*', function(req, res, next) {
// We create a factory for every request and pass it to the view
// This quickly becomes hard to manage if you need it in multiple parts of the code,
// It would be much better if every part of the application that needs access
// could simply import the singleton using the standard `require` or get it from some kind
// of global scope that is created per request and doesn't get polluted when things are done async
var perRequestFactory = factory();
var view = new View({
factory: perRequestFactory,
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 = options.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