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!
Edit: Had to make a few changes to get the Base code from dc5 to work. System works but for main I'm getting this error on the inherits call:
util.js:555
ctor.prototype = Object.create(superCtor.prototype, {
^
TypeError: Object prototype may only be an Object or null
at Function.create (native)
at Object.exports.inherits (util.js:555:27)
/controllers/system/index.js:
var util = require( 'util' ),
system = { };
system.index = function( req, res, next ) {
res.render( 'main' );
};
module.exports = system;
/controllers/main/index.js:
var util = require( 'util' ),
system = require( './../system/index' ),
main = { };
util.inherits( main, system );
module.exports = main;