Is There An Idiomatic Command Pattern Implementation For JavaScript?


I’ve been looking for a JavaScript Command Pattern implementation for a while now. If you google that term (or click that link) you’ll find a handful or more, that I simply don’t like. Granted, the implementations that I’ve found do work, but there’s always something about them that bothers me and makes me scream “NOOOO!!!!!!”.

So I’m wondering: is there a truly idiomatic JavaScript command pattern implementation available anywhere? Or do I just need to write my own?

In case there isn’t, I whipped up a simple stupid version of what it might look like if I were going to build one, in JSFiddle:

(Click on the link if you’re in an RSS reader)

You can see the code is simple, as I think it should be. Run the ‘Result’ tab if you’re reading this in the browser. Enter some text and click the “Say It” button. It does nothing more than show the text you entered. The point is not what it makes the app do, but how it does it. This provides a decoupled command pattern implementation, using JavaScript idioms like callback functions and key-value/hash/json objects to store registrations and all that jazz.

Of course there’s a lot missing from this code (like unregistering a command handler) and the core of this code is a very simple, stupid, single handler version of what’s already available in the Backbone.Events code – just with different semantics in the names of the methods.

So I ask – is there a good, idiomatic JavaScript implementation of a command pattern? One that allows proper decoupling of the command handler, command message and calling for the command to be executed? One that doesn’t rely on adding “class” semantics to JavaScript? One that doesn’t couple the name of the method being called as a command directly to the calling of the command (srsly… how could that even be called a command pattern?)?

Please let me know via the comments before I continue down the path of rebuilding something that I should be looking at / using.

Introduction To Composite JavaScript Apps