Skip to content

Instantly share code, notes, and snippets.

@sveisvei
Forked from mumrah/gist:361752
Created April 10, 2010 20:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sveisvei/362266 to your computer and use it in GitHub Desktop.
Save sveisvei/362266 to your computer and use it in GitHub Desktop.
var fs = require('fs');
var url = require('url');
var sys = require('sys');
var http = require('http');
require('./ejs'); // EJS, http://embeddedjs.com/
/*
* Server-side controller methods
*/
var routes = new function(){
this.routes = {};
this.register = function(route, callback){
this.routes[route] = callback;
}
}
routes.register('/', function(env){
var tmpl = fs.readFileSync('base.html'); // An minimal HTML template, puts $head_js in the <head>
var html = new EJS({text: tmpl}).render({head_js: client.toString()});
env.res.writeHead(200, {'Content-Type': "text/html"});
env.res.write(html);
env.res.close();
});
routes.register('/test',function(env){
env.res.writeHead(200, {'Content-Type': "text/plain"});
env.res.write("Hello, Indeed!");
env.res.close();
});
routes.register('/favicon.ico',function(env){
env.res.writeHead(200, {'Content-Type': "image/png"});
env.res.close();
});
/*
* Client-side functions
*/
var client = new function(){
this.funcs = [];
this.register = function(name, func){
this.funcs.push(func);
var func_str = func.toString();
func.toString = function(){ return "var " + name + " = " + func_str + ";"}
}
this.toString = function(){
var js_out = "";
this.funcs.forEach(function(func){
js_out += func.toString();
});
return js_out;
}
}
client.register('foo',function(){
var div = $(document.body).append("<div>Hello, World</div>");
div.bind('click',function(e){
$.ajax({
url: '/test',
success: function(d){ $(div).append("<div>#"+d+"#</div>"); }
});
});
});
client.register('onload',function(){
foo();
});
http.createServer(function(req, res){
var url_parse = url.parse(req.url,true);
var env = {
req : req,
res : res,
path : url_parse.pathname,
url_params : (url_parse.query) ? url_parse.query : {}
};
if(req.method == 'GET') {
for(route in routes.routes) {
if(env.path == route) {
routes.routes[route].call(this, env);
}
}
}
}).listen(8000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment