Created
March 6, 2011 19:42
-
-
Save ProjectMoon/857580 to your computer and use it in GitHub Desktop.
Fuller code example showing the MVC implementation
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
function endsWith(str, suffix) { | |
return str.substr(-1) === suffix; | |
} | |
function ActionController(baseRoute, actions) { | |
this._baseRoute = baseRoute; | |
this._actions = actions; | |
} | |
ActionController.prototype.boot = function(app) { | |
var baseRoute = this._baseRoute; | |
baseRoute = endsWith(baseRoute, '/') ? baseRoute : baseRoute + '/'; | |
console.log('baseroute is: ' + baseRoute); | |
for (actionName in this._actions) { | |
var action = this._actions[actionName]; | |
var route = baseRoute + actionName; | |
if (action.get && typeof(action.get) == 'function') { | |
app.get(route, action.get); | |
} | |
if (action.post && typeof(action.post) == 'function') { | |
app.post(route, action.post); | |
} | |
if (action.put && typeof(action.put) == 'function') { | |
app.put(route, action.put); | |
} | |
if (action.del && typeof(action.del) == 'function') { | |
app.del(route, action.del); | |
} | |
} | |
} | |
//Expose globally | |
exports.ActionController = ActionController; |
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
//This is a pared-down example of my application's file. | |
var app = module.exports = express.createServer(); | |
//Configure app... | |
//Define controller. | |
var UserController = new ActionController('/users/', { | |
show: { | |
get: function(req, res) { | |
mg.connect('mongodb://localhost/local'); | |
User.find({}, function(errors, users) { | |
mg.connection.close(); | |
res.render('index', { | |
title: 'Example Page', | |
users: users | |
}); | |
}); | |
} | |
} | |
} | |
//There are other actions defined, but I have omitted them for this example. | |
//This initializes everything. | |
UserController.boot(app); | |
if (!module.parent) { | |
app.listen(3000); | |
console.log("Express server listening on port %d", app.address().port) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment