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.


Post Footer automatically generated by Add Post Footer Plugin for wordpress.

About Derick Bailey

Derick Bailey is an entrepreneur, problem solver (and creator? :P ), software developer, screecaster, writer, blogger, speaker and technology leader in central Texas (north of Austin). He runs SignalLeaf.com - the amazingly awesome podcast audio hosting service that everyone should be using, and WatchMeCode.net where he throws down the JavaScript gauntlets to get you up to speed. He has been a professional software developer since the late 90's, and has been writing code since the late 80's. Find me on twitter: @derickbailey, @mutedsolutions, @backbonejsclass Find me on the web: SignalLeaf, WatchMeCode, Kendo UI blog, MarionetteJS, My Github profile, On Google+.
This entry was posted in Backbone, Design Patterns, Javascript, Principles and Patterns. Bookmark the permalink. Follow any comments here with the RSS feed for this post.
  • Peter Rust

    Derick,

    I’m not sure what your use-case is, but the most common use-case of the Command pattern is to implement an undo/redo stack. This usually means that the command has to be an object — not just a function — with a pair of methods: execute()/unexecute(), do()/undo(), etc. Also, the command object usually stores some state during the execute(), which is used by unexecute() to restore things back to the original state. I’m not saying it can’t be done with a simple function, but it usually ends up more complicated than the object approach.

    I don’t know if that’s what you mean by adding “class” semantics to Javascript, but it can be implemented in an idiomatic way using prototypical inheritance, using _.extend() on a prototype, etc…

    See the discussion on http://c2.com/cgi/wiki?CommandPattern about using a “glorified function” vs an object, and the “Undo and redo actions” paragraph here: http://www.oodesign.com/command-pattern.html. There is a concrete example implementation of a command pattern with an undo/redo stack implemented here, which more-or-less lines up with what I was thinking and with most of the UML diagrams for the Command Pattern floating around the web: http://www.dofactory.com/Patterns/PatternCommand.aspx#_self2 (unfortunately it’s in C#, but I’m sure you can look beyond that :-)

    – peter

    • http://mutedsolutions.com Derick Bailey

      Hey Peter - 

      I’m thinking I should have been more specific about the term… I’m aware of the standard ‘undo’ functionality that comes with most discussion of command patterns. That’s only one example of what a command can do, though. Not all commands need to have that. The undo semantics are useful, but optional. (Honestly, I get tired of every discussion of command patterns devolving into ‘undo’… but that’s another discussion, in itself :)

      In my case, I’m referring more to the “command” pattern from messaging architectures (in-memory or message-bus), such as the code that I’ve written in C# / Winforms apps for several years now: http://lostechies.com/derickbailey/2009/12/23/understanding-the-application-controller-through-object-messaging-patterns/ (side note: I know there are some things not quite right in that article… it is 2 years old, after all)As for class semantics, I mean this: http://jsclass.jcoglan.com/command.html It drives me crazy when people want to try and build “class” into JavaScript, and then require that you “inherit” i.e. “class”y syntax such as Java / C#, to use the functionality that they provide

  • http://twitter.com/vkornov Victor Kornov

    this days I simply go for jQuery’s custom events (pseudo-code):
    var controller = {
        handler: function(data) {
              console.log(data);
        }
    }
    var model = {
         event_happens: function() {
                $(this).triggerHanler(‘event_command’, { data: ‘goes here’ });
         }
    };
    $(model).bind(‘event_command’, controller.handler);
    model .event_happens();

  • Adam Tybor

    This just looks like standard event handling.  Subscribe to a command with a callback, trigger the callback.  Outside of linguistic semantics around a command vs event, what is the difference with your implementation?

    • http://mutedsolutions.com Derick Bailey

      other than the semantics, it is the same – hence my mentioning that in the post :)

      but semantics are important, and a simple example like this isn’t going to have any differentiating features. a more feature complete example might… maybe… i dunno yet. i haven’t found one that I like, yet.

  • http://domenicdenicola.com/ Domenic Denicola

    If you’re not doing undo-style examples, and you are in fact doing a messaging-type system, then this is definitely just event handling. In JavaScript circles this is often known as “pubsub.”

    So, basically, the idiomatic way of doing commands in JavaScript is to rephrase your problem in terms of events.

    • http://mutedsolutions.com Derick Bailey

      there’s far more to messaging then just pub/sub. point-to-point (commands) and request/response are very valuable patterns that also have their place. there’s a semantic difference that is significant, and there’s often an implementation difference – though my simple example here obviously hasn’t shown one – hence my asking for a good, idiomatic implementation instead of just using what i provided as an example.

      just because we technically can do everything as events doesn’t mean we should. this leads to terrible code. believe me – or my former coworkers. you can ask many of them about the horrible things i did to our systems by ignoring request/response and saying events or events + commands were good enough. :-/

      semantics are important as they often lead to technical and implementation differences.

  • Anonymous

    I just ran across a Node.js app that is using the command pattern (and also a dependency injector, which is also interesting).

    And it’s you’re luck day, because they wrote it in CoffeeScript!!!

    https://github.com/idflood/ThreeNodes.js

    Enjoy

    • http://mutedsolutions.com Derick Bailey

      well, fortunately I know how to read JavaScript :D

      that implementation is the same as what I showed here. maybe i should just flesh mine out a bit and be done with it.

      • Dave Cadwallader

        Hey Derick, 
        I’m really curious to hear what you’ve found out since you wrote this.  I’m currently migrating a Flex-based UI to a JS architecture.  

        The Flex UI used a framework called Robotlegs which relied heavily on the Command Pattern, which provided a nice separation between a Context object (whose sole job is to map events to command classes) and the Command objects themselves which were just small single-purpose classes with an “execute()” method.  

        This made unit testing a breeze, with a nice clean decoupled architecture.  I’m seeing part of the picture with the Backbone.Events code (and your Event Aggregator post, which is sort of like a Robotlegs Context) but I’d like to take it one step further and have separate Commands instead of callback functions that live within my view code.  

        If you haven’t found anything yet, I’d be very interested in collaborating to build what we need!

        Thanks,
        Dave

        • Dave Cadwallader

          Just saw that your implementation of Marionette.AppRouter handles this decoupling nicely using the “controller” object.

          However, this only works for Routes (URLs) and not for plain old application events.

          I’d wonder if we could take this concept one step further, and allow an Application instance to bind “events” to “controller methods”.  This would allow non-view “commands” to respond to application events dispatched onto the Event Aggregator (“vent”).

          For instance, I might have a page that has a form and a “Save” button.  When the button is clicked, I want to dispatch a “Save” event that gets picked up elsewhere by some non-view code.

          On another note, do you support nested Marionette Applications?  For instance, in a multi-tabbed layout, where the outer container is the “parent app” and each tab is a “child app”.  The children want to have their own “vent” to handle events that only concern the tab, but they also want the ability to communicate with the parent shell for system-wide events such as opening a new tab, etc.

          Thanks for the great articles and framework!

  • Placeboaddict

    Hi Derick.

    Feeling a bit “future-man-ish” commenting on this old post. My experience looking around for a more than bare minimum implementation is identical.

    I was recently brought on a small project, where no structure is in place at all, and running through everything i immediately thought of the CMD-pattern, as i have used it several times Java/C#. It’s an SPA built on knockout with no separation of concerns, ViewModels are doing everything on a “because they are there” basis.
    In the core module(s) there is a similar situation, why i thought to do a couple of executors and clean everything up.

    Did your past research here amount to anything, or have you found something new and exciting you would be willing to share? To me it seems the call-back paradigm is dominating the js scene, so any “classical” OO disciplines gets taken out back and shot when uttered:-)

    In any case, thanks for bringing this up! Two years ago xD

    • Placeboaddict

      Another thing to notice, in my opinion, is that every example more or less binds directly to markup or whatever what ever MV* framework used. Basically i would expect people to be decoupling them from their strictly logical layers…. is this wrong, or am i just on into callbacks enough?

    • geekdave

      @Placeboaddict:disqus : Check out Backbone.Geppetto, a plugin I wrote that solves this exact problem: http://modeln.github.io/backbone.geppetto/