From ActionScript 3.0 to JavaScript Chain of Responsibility: Part II The Help Desk
I’ve always liked JavaScript, but after going through this last project of creating a design pattern with JS, I find that I like ActionScript 3.0 even more than I did before. The biggest problems that I encountered with JavaScript is that different users slipped in different frameworks (e.g., Prototype.js) and didn’t seem to mention it. My goal was to create a JS design pattern with pure unadulterated JavaScript—not using JQuery, JSon or some other helpful framework. Now, don’t get me wrong—I appreciate a good framework as much as the next guy. However, when I’m trying to create a design pattern for a general language like JavaScript, I’d rather not have to have readers run out and get one framework or another. I wanted this to work with Plain Vanilla JavaScript. So that’s what you’re going to get.
To get started, I took a look at some articles on JavaScript and classes, inheritance and OOP in general. Then I looked at some implementations of JavaScript with a Chain of Responsibility pattern. A lot of them didn’t make a bit of sense, and that’s when I realized that they were slipping in different “helpers,” and so I went back to the most basic JavaScript OOP I knew of–the 1999 book, JavaScript Objects by Nakhimovsky and Myers. Starting there, I pretty much followed that Chain of Responsibility pattern we had in Part I of this two-part series. However, instead of a mobile browser detector, I created a “Help Desk.”
Before continuing, take a look at the “Help Desk” app made with the JS CoR:
![]()
Inheritance is a ‘IS-A’
First I made an abstract Handler class using a single concrete and single abstract method. It seemed to me that classes in JavaScript could be abstract simply by adding a method with no content. I came up with the following class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | function Handler()
{
//Handler 'abstract class'
}
Handler.prototype.setSuccessor=function(successor)
{
this.successor=successor;
}
Handler.prototype.handleRequest=function(req)
{
//Abstract method overridden in concrete implementation
} |
I realize that it looks strange compared to more mature OOP languages like ActionScript 3.0 (not to mention Java and C++), but remember, I’m using pure native JavaScript. You create the class by the simple expedient of a function. Then, I create the methods for the class by using a Class.prototype. The class Handler now has the setSuccessor and handleRequest methods, just as we had in the ActionScript 3.0 version. So, while it looks a little goofy for creating classes and their methods and properties, that’s how it’s done.
So far so good, and it’s not rocket science. However, the next part gets a little dicey and may pop a few brain nodes. When you extend a class in JavaScript, you first instantiate the parent class. As we all know, you do not instantiate abstract classes or any other interface. They’re extended or implemented. However, that’s not the case with JavaScript. Take a look at this first child class of Handler:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | //AS3DP inherits handler
AS3DP.prototype= new Handler();
function AS3DP()
{
//AS3DP 'class'
}
AS3DP.prototype.handleRequest=function(req)
{
this.req=req;
if(this.req=="as3dp")
{
document.write("Naturally you want to read <em>ActionScript 3.0 Design Patterns</em> and visit our blog at as3dp.com.");
}
else if(this.successor != null)
{
document.write("Not AS3DP<br/>");
this.successor.handleRequest(this.req);
}
} |
If you recall, basic design pattern principles, a child class “Is-A” parent class. When a JavaScript object (like AS3DP) is instantiated, it is done by declaring itself as a new Handler(). So rather than becoming a child of the parent through extension, JavaScript uses the object prototype to declare itself as an instance of the parent. It’s actually easier to see that a child class indeed “Is-A” parent because the prototype declares itself as such.
As we have seen, the methods and properties have been created outside of the class constructors. Instead of being in the class, they are in the prototype. For now, you can think of the class as the “concept of an object” and it creates and stores the properties for that concept in prototypes. So, knowing that, we can create the rest of the concrete handlers:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 | //Game inherits Handler
Game.prototype= new Handler();
function Game()
{
//Game 'class'
}
Game.prototype.handleRequest=function(req)
{
this.req=req;
if(this.req=="game")
{
document.write("As the states change, you want a good state machine like the State Design Pattern.");
}
else if(this.successor != null)
{
document.write("Not State pattern<br/>");
this.successor.handleRequest(this.req);
}
}
//Algorithm inherits Handler
Algorithm.prototype= new Handler();
function Algorithm()
{
//Algorithm 'class'
}
Algorithm.prototype.handleRequest=function(req)
{
this.req=req;
if(this.req=="algorithm")
{
document.write("The Strategy Design Pattern lets you access different algorithms directly without having to use conditional statements!");
}
else if(this.successor != null)
{
document.write("Not Strategy pattern<br/>");
this.successor.handleRequest(this.req);
}
}
//Factory inherits Handler
Factory.prototype= new Handler();
function Factory()
{
//Factory 'class'
}
Factory.prototype.handleRequest=function(req)
{
this.req=req;
if(this.req=="factory")
{
document.write("The Factory Method design pattern will unlink the request to build an object from the actual object creation.");
}
else if(this.successor != null)
{
document.write("Not Factory<br/>");
this.successor.handleRequest(this.req);
}
}
//ToInterface inherits Handler
ToInterface.prototype= new Handler();
function ToInterface()
{
//ToInterface 'class'
}
ToInterface.prototype.handleRequest=function(req)
{
this.req=req;
if(this.req=="tointerface")
{
document.write("The first principle is to <em>Program to the interface and not the implementation.</em> When you declare a new object, type it to the object's parent class; not the object itself.");
}
else if(this.successor != null)
{
document.write("Not Program to Interface<br/>");
this.successor.handleRequest(this.req);
}
}
//Truth inherits Handler
Truth.prototype= new Handler();
function Truth()
{
//Truth 'class'
}
Truth.prototype.handleRequest=function(req)
{
document.write("You know I can't handle the truth! Go visit a muse, a swami, or 3-year old.<br/>");
} |
As you no doubt have noticed, this Chain of Responsibility implementation is not about mobile devices and their languages. Instead, it’s a “Help Desk” that I think is more typical of what you may actually use a CoR pattern for—either in JavaScript or ActionScript 3.0.
All that’s left is to do with the JavaScript is to create instances of the different handlers and set the chain of successors. The “client” that makes the requests is the HTML5 UI.
1 2 3 4 5 6 7 8 9 10 11 12 13 | //'Instantiate Concrete Handlers' var as3dp = new AS3DP(); var game=new Game(); var algorithm=new Algorithm(); var factory=new Factory(); var tointerface=new ToInterface(); var truth=new Truth(); //Set successors as3dp.setSuccessor(game); game.setSuccessor(algorithm); algorithm.setSuccessor(factory); factory.setSuccessor(tointerface); tointerface.setSuccessor(truth); |
You can set up the successors in any way you want except the last one has to be to the Truth class. It has no successor and is meant to be the caboose of the chain. Before going on, place all of the JavaScript into a single file and save it as “HelpDesk.js” and put it in the same folder (directory) as the HTML5 program that follows.
The HTML5 Client
Like most work with JavScript, the UI is in HTML. This is no different. All it does is to call the top of the chain (AS3DP instance) and make a request. All of the requests look like the following:
onclick=”as3dp.handleRequest(‘algorithm’);
The click handler calls the top of the chain, and the Chain of Responsibility just chugs on through until it finds what you want. Here’s the whole HTML5 code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | <!DOCTYPE HTML>
<html>
<head>
<style type="text/css">
body {
font-family:Verdana, Geneva, sans-serif;
color:#1D232;
background-color:#dddcc5;
font-size:12px;
}
h2 {
font-family:"Arial Black", Gadget, sans-serif;
font-size:24px;
text-align:center;
color:#611427;
}
form {
color:#6A6A61;
}
h3 {
background-color:#611427;
color:#958976;
font-size:18px;
}
</style>
<script type="text/javascript" src="HelpDesk.js">
</script>
<meta charset="UTF-8">
<title>Billz Help Desk</title>
</head>
<body>
<header>
<h2>Billz Help Desk</h2>
</header>
<article>
<header>
<h3> Chain of Responsibility: JavaScript</h3>
</header>
<section> This is a simple Chain of Responsibility (CoR) application. Each button represents a different request that the CoR will handle. In this case, the help is in the form of a 'Help Desk' and the CoR finds the appropriate response to the query.<br/>
<br/>
<form>
<input type=button value="Make Request" onclick="as3dp.handleRequest('as3dp');" />
How do I learn about design patterns for ActionScript 3.0 <br/>
<input type=button value="Make Request" onclick="as3dp.handleRequest('game');" />
I'm making a game where states keep changing. What would be a good design pattern for dealing with changing states?<br/>
<input type=button value="Make Request" onclick="as3dp.handleRequest('algorithm');" />
My app involves a lot of problem solving with different algorithms? What's a good pattern for dealing with multiple algorithms?<br/>
<input type=button value="Make Request" onclick="as3dp.handleRequest('factory');" />
Whenever I create a new object with my Client object, I build up dependencies. Is there a pattern to avoid such dependencies?<br/>
<input type=button value="Make Request" onclick="as3dp.handleRequest('tointerface');" />
What is a primary guiding design pattern principle?<br/>
<input type=button value="Make Request" onclick="as3dp.handleRequest('truth');" />
I want to know the truth!<br/>
</form>
</section>
<br/>
<section>The CoR pattern works sequentially so that as it moves through the chain, you can see each rejected attempt to find the correct handler. (Normally, you wouldn't see those rejected handlers.) It is a very easy pattern to update and add additional handlers.</section>
</article>
</body>
</html> |
So, now you’re all set to use JavaScript for design patterns. The plain vanilla JS has limitations doing OOP, but you can harness it and bend it to your OOP will. The many different frameworks that work in conjunction with basic JavaScript will make it look more like an OOP language, but you can get by without. There’s a lot to be done with even the most unadorned JavaScript, and I tested the app on an iPhone, and it works fine. However, I’ll bet that several of you can find better ways to handle either the JavaScript or HTML5 (or both) with design patterns, and we’d like to hear from you. Naturally, if you have a favored framework that makes OOP work more efficient, let us know—even better send a design pattern example.
Related posts:



Bill Sanders
Hi Bill,
this series of articles – from ActionScript to JavaScript – couldn’t be in a better timing for me! I just switched my focus from AS3 to JS and I’m facing a lot of challenges to adapt my DP knowledge to this curious world. A lot of cool stuff has been done.
When I switch from one language or paradigm to another, I ask my self “Are the old concepts still valid here? Which are the advantages that I can exploit and the pitfalls that I must purge?”. Sometimes I find my self dreaded facing an “ugly” piece of code but most of the times I am pleased to see how a concept becomes reality in very ingenious way.
This post has given me a cool insight and inspired me to make a follow up. I will post it on my blog and I’ll let you know when it’s done – but it will be in portuguese.
Regards,
Hi Bill,
I’m glad to hear it helped, but don’t give up on AS3 just yet. If you have Flash 5.5, you’ll see how you can create AIR apps for mobile devices using AS3 (my next post will be illustrating this), and JS has its own Tower of Babel as different implementations and frameworks vie for dominance.
As for Design Patterns and OOP concepts transcending languages, I believe they do. What DP/OOP does is to provide a different way of approaching a problem to solve or task to accomplish. It’s a way of thinking about programming. Most of what I learned about Design Patterns was using Java, and most of the GoF book uses SmallTalk and (some C++) as the primary examples; so I had to first learn enough Java so that I could translate the concepts into AS3. With JavaScript, I moved on to the next step–taking AS3 examples and translating them into JS. The difficulty was in realizing that JS might actually be JS sitting on top on one framework or another or JQuery or JSon.
However, I think learning other languages like JavaScript and C# is always a good idea. An even better idea is working through them with OOP/DP–then you really get to know them!
Kindest regards,
Bill
This hands-on introduction to design patterns is for experienced Flash developers ready to tackle sophisticated programming techniques with ActionScript 3.0. The step-by-step process allows readers to construct truly elegant solutions for their Flash applications in no time.
Hey Mercadeo!
¿Did I just get spammed en Español? ¡Ay, caramba! ¿Que pasa?
Memo….