How to create extendable controllers in ExpressJS
I'm new to Node and I'm trying to create an MVC app with ExpressJS
(http://expressjs.com/). I'm using the same folder structure as the MVC
example (https://github.com/visionmedia/express/tree/master/examples/mvc)
on GitHub.
In my controllers folder, I have 2 folders: main and system. What I'd like
is to have a base controller defined in /controllers/system/index.js and
have /controllers/main/index.js inherit the system controller. Every other
module will extend system and override a few functions to generate a page.
In another tutorial I found the following code.
Base.js
var _ = require("underscore");
module.exports = {
name: "base",
extend: function(child) {
return _.extend({}, this, child);
},
run: function(req, res, next) {
}
};
Home.js
var BaseController = require("./Base"),
View = require("../views/Base"),
model = new (require("../models/ContentModel"));
module.exports = BaseController.extend({
name: "Home",
content: null,
run: function(req, res, next) {
model.setDB(req.db);
var self = this;
this.getContent(function() {
var v = new View(res, 'home');
v.render(self.content);
})
},
getContent: function(callback) {
var self = this;
this.content = {};
model.getlist(function(err, records) {
if(records.length > 0) {
self.content.bannerTitle = records[0].title;
self.content.bannerText = records[0].text;
}
model.getlist(function(err, records) {
var blogArticles = '';
if(records.length > 0) {
var to = records.length < 5 ? records.length : 4;
for(var i=0; i<to; i++) {
var record = records[i];
blogArticles += '\
<div class="item">\
<img src="' + record.picture + '" alt="" />\
<a href="/blog/' + record.ID + '">' +
record.title + '</a>\
</div>\
';
}
}
self.content.blogArticles = blogArticles;
callback();
}, { type: 'blog' });
}, { type: 'home' });
}
});
How do you do this without Underscore's extend function? Does Express have
a built in method to extend modules? I'm using doT.js for templating so I
don't want to include another large library for one function.
Thanks!
No comments:
Post a Comment