An Idiomatic JavaScript Command Pattern
I'm trying to find or build an idiomatic, simple and elegant command pattern in JavaScript. All of the implementations I've found so far, are terrible. I'm not sure this is any better, but it's a start.
by derickbailey
HTML
<input type="text" id="saythis">
<button id="sayit">Say It!</button>
<div id="showit"></div>
JavaScript
// a very small, idiomatic command pattern implementation
Executor = (function(){
var executor = {};
var commands = {};
executor.handle = function(commandName, callback){
var commandHandler = {
ref: this,
callback: callback
};
commands[commandName] = commandHandler;
};
executor.execute = function(commandName, data){
var cmd = commands[commandName];
if (cmd){
cmd.callback.call(cmd.ref, data);
}
};
return executor;
})();
// a module to represent the "form"
(function(Executor){
var buttonEl = $("#sayit");
var textEl = $("#saythis");
buttonEl.click(function(e){
e.preventDefault();
Executor.execute("doit", textEl.val());
});
})(Executor);
// a module to represent a view, which responds to a command
(function(Executor, $){
// a command handler ... it's a function! cause, hey...
// JavaScript is all about functions.
var showTheText = function(data){
var el = $("#showit");
el.text("You told me to say: '" + data + "', so I did.");
};
// handle the command
Executor.handle("doit", showTheText);
})(Executor, jQuery);