Skip to content

Instantly share code, notes, and snippets.

@jmarnold
Created October 21, 2011 02:46
Show Gist options
  • Save jmarnold/1302990 to your computer and use it in GitHub Desktop.
Save jmarnold/1302990 to your computer and use it in GitHub Desktop.
An old js dsl example
jBus.routing = new (function() {
function lazy(builder) {
this.builder = builder;
this.buildWith = function(func) {
this.builder = func;
};
this.value = function() {
return this.builder();
};
}
var graph = new lazy(function() {
return new jBusRegistry().buildGraph();
});
function jBusHandler(type, action) {
this.type = type;
this.action = action;
this.handle = function(msg) {
this.action(msg);
};
}
function jBusGraph(handlers) {
this.handlers = handlers;
this.handlersFor = function(type) {
var self = this;
var typedHandlers = [];
for(var i = 0; i < self.handlers.length; i++) {
var h = self.handlers[i];
if(h.type == type) {
typedHandlers.push(h);
}
}
return typedHandlers;
};
}
function jBusRegistry() {
this.handlers = [];
this.on = function(type, action) {
this.handlers.push(new jBusHandler(type, action));
};
this.buildGraph = function() {
var self = this;
return {
handlers: self.handlers
};
};
}
return {
initialize: function(configure) {
var registry = new jBusRegistry();
configure.call(registry);
graph.buildWith(registry.buildGraph);
},
handle: function(msg) {
if(!graph) {
graph = new jBusRegistry().buildGraph();
}
var socketMsg = eval('(' + msg.data + ')');
var message = eval('(' + socketMsg.Message + ')');
// handle
var handlers = graph
.value()
.handlersFor(socketMsg.Type);
for(var i = 0; i < handlers.length; i++) {
handlers[i].handle(message);
}
}
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment