-
-
Save dazld/6239592 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 messy code | |
// factory.js | |
// | |
// 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 = []; | |
} | |
} | |
}; | |
// view.js | |
var Factory = require('./factory'); | |
var View = require('backbone').View; | |
module.exports = View.extend({ | |
initialize: function (args) { | |
this.viewState = args.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) { | |
// 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 | |
}); | |
var responseTime = Math.random() * 2500; // random response time | |
// Simulate async tasks | |
setTimeout(function () { | |
res.send(perRequestFactory.serializeModels()); | |
}, responseTime); | |
}); | |
app.listen(8000); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment