DerbyJS — Node.js MVC Framework
Express.js is a popular node frameworks which uses middleware concept to enhance functionality of applications. Derby is a new sophisticated Model View Controller (MVC) framework which is designed to be used with Express as it’s middleware. Derby also comes with the support of Racer, data synchronization engine, and Handlebars-like template engine among many other features.
Derby.js Installation
Let’s set up a basic Derby application architecture without the use of scaffolding. Usually project generators are confusing when people just start to learn a new comprehensive framework. This is a bare minimum “Hello World” application tutorial that still illustrates Derby skeleton and demonstrates live-templates with websockets.
Of course we’ll need Node.js and NPM which can be obtained at nodejs.org. To install derby globally run:
$ npm install -g derby
To check the installation:
$ derby -V
My version as of April 2013 is 0.3.15. We should be good to go to creating our first app!
File Structure in a Derby.js App
This is the project folder structure:
project/
-package.json
-index.js
-derby-app.js
views/
derby-app.html
styles/
derby-app.less
Dependencies for The Derby.js Project
Let’s include dependencies and other basic information in package.json file:
{
"name": "DerbyTutorial",
"description": "",
"version": "0.0.0",
"main": "./server.js",
"dependencies": {
"derby": "*",
"express": "3.x"
},
"private": true
}
Now we can run npm install
which will download our dependencies into node_modules folder.
Views in Derby.js
Views must be in views folder and they must be either in index.html under a folder which has the same name as your derby app JavaScript file, i.e., views/derby-app/index.html
, or be inside of a file which has the same name as your derby app JS file, i.e., derby-app.html.
In this example “Hello World” app we’ll use <Body:>
template and {message}
variable. Derby uses mustach-handlebars-like syntax for reactive binding. index.html looks like this:
<Body:>
<input value="{message}"><h1>{message}</h1>
Same thing with Stylus/LESS files, in our example index.css has just one line:
h1 {
color: blue;
}
To find out more about those wonderful CSS preprocessors check out documentation at Stylus and LESS.
Building The Main Derby.js Server
index.js is our main server file, and we begin it with an inclusion of dependencies with require()
function:
var http = require('http'),
express = require('express'),
derby = require('derby'),
derbyApp = require('./derby-app');
Last line is our derby application file derby-app.js.
Now we’re creating Express.js application (v3.x has significant differences between 2.x) and an HTTP server:
var expressApp = new express(),
server = http.createServer(expressApp);
Derby uses Racer data synchronization library which we create like this:
var store = derby.createStore({
listen: server
});
To fetch some data from back-end to the front-end we instantiate model object:
var model = store.createModel();
Most importantly we need to pass model and routes as middlewares to Express.js app. We need to expose public folder for socket.io to work properly.
expressApp.
use(store.modelMiddleware()).
use(express.static(__dirname + '/public')).
use(derbyApp.router()).
use(expressApp.router);
Now we can start the server on port 3001 (or any other):
server.listen(3001, function(){
model.set('message', 'Hello World!');
});
Full code of index.js file:
var http = require('http'),
express = require('express'),
derby = require('derby'),
derbyApp = require('./derby-app');
var expressApp = new express(),
server = http.createServer(expressApp);
var store = derby.createStore({
listen: server
});
var model = store.createModel();
expressApp.
use(store.modelMiddleware()).
use(express.static(__dirname + '/public')).
use(derbyApp.router()).
use(expressApp.router);
server.listen(3001, function(){
model.set('message', 'Hello World!');
});
Derby.js Application
Finally, Derby app file which contains code for both a front-end and a back-end. Front-end only code is inside of app.ready()
callback. To start, let’s require and create an app. Derby uses unusual construction (not the same familiar good old module.exports = app
):
var derby = require('derby'),
app = derby.createApp(module);
To make socket.io magic work we need to subscribe model attribute to its visual representation, in other words bind data and view. We can do it in the root route, and this is how we define it (patter is /
, a.k.a. root):
app.get('/', function(page, model, params) {
model.subscribe('message', function() {
page.render();
})
});
Full code of derby-app.js file:
var derby = require('derby'),
app = derby.createApp(module);
app.get('/', function(page, model, params) {
model.subscribe('message', function() {
page.render();
})
});
Launching Hello World App
Now everything should be ready to boot our server. Execute node .
or node index.js
and open a browser at http://localhost:3001. You should be able to see something like this: http://cl.ly/image/3J1O0I3n1T46.
Passing Values to Back-End in Derby.js
Of course static data is not much, so we can slightly modify our app to make back-end and front-end pieces talks with each other.
In the server file index.js add store.afterDb
to listen to set
events on message
attribute:
server.listen(3001, function(){
model.set('message', 'Hello World!');
store.afterDb('set','message', function(txn, doc, prevDoc, done){
console.log(txn)
done();
})
});
Full code of index.js after modifications:
var http = require('http'),
express = require('express'),
derby = require('derby'),
derbyApp = require('./derby-app');
var expressApp = new express(),
server = http.createServer(expressApp);
var store = derby.createStore({
listen: server
});
var model = store.createModel();
expressApp.
use(store.modelMiddleware()).
use(express.static(__dirname + '/public')).
use(derbyApp.router()).
use(expressApp.router);
server.listen(3001, function(){
model.set('message', 'Hello World!');
store.afterDb('set','message', function(txn, doc, prevDoc, done){
console.log(txn)
done();
})
});
In Derby application file derby-app.js add model.on()
to app.ready()
:
app.ready(function(model){
model.on('set', 'message',function(path, object){
console.log('message has been changed: '+ object);
})
});
Full derby-app.js file after modifications:
var derby = require('derby'),
app = derby.createApp(module);
app.get('/', function(page, model, params) {
model.subscribe('message', function() {
page.render();
})
});
app.ready(function(model) {
model.on('set', 'message', function(path, object) {
console.log('message has been changed: ' + object);
})
});
Now we’ll see logs both in the terminal window and in the browser Developer Tools console. The end result should look like this in the browser: http://cl.ly/image/0p3z1G3M1E2c, and like this in the terminal: http://cl.ly/image/322I1u002n38.
For more magic in the persistence area, check out Racer’s db property. With it you can set up an automatic synch between views and database!
Let me know if you’re interested in any specific topic for future blog post and don’t forget to checkout my JavaScript books:
The full code of all the files in this Express.js + Derby Hello World app is available as a gist at https://gist.github.com/azat-co/5530311.