<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>The Coffeescripter &#187; Javascript</title>
	<atom:link href="http://coffeescripter.com/category/javascript/feed/" rel="self" type="application/rss+xml" />
	<link>http://coffeescripter.com</link>
	<description>Just another developer blog</description>
	<lastBuildDate>Sun, 08 Aug 2010 11:40:16 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Dependency injection and IoC in Javascript</title>
		<link>http://coffeescripter.com/2010/08/dependency-injection-and-ioc-in-javascript/</link>
		<comments>http://coffeescripter.com/2010/08/dependency-injection-and-ioc-in-javascript/#comments</comments>
		<pubDate>Sun, 08 Aug 2010 11:40:16 +0000</pubDate>
		<dc:creator>Andy</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Object Oriented]]></category>
		<category><![CDATA[dependency injection]]></category>
		<category><![CDATA[ioc]]></category>

		<guid isPermaLink="false">http://coffeescripter.com/?p=186</guid>
		<description><![CDATA[There has been some talk lately about DI and IoC in Javascript, and other dynamic languages such as Ruby and Python. A popular opinion seems to be that these concepts are obsolete in dynamic languages, mainly because you can alter an object at runtime. This certainly makes testing easier, but testability isn&#8217;t the main goal [...]]]></description>
			<content:encoded><![CDATA[<p>There has been some talk lately about DI and IoC in Javascript, and other dynamic languages such as Ruby and Python. A popular opinion seems to be that these concepts are obsolete in dynamic languages, mainly because you can alter an object at runtime. This certainly makes testing easier, but testability isn&#8217;t the main goal of DI and IoC, it&#8217;s more of a nice side effect, and a proof of that you&#8217;re doing it right.</p>
<p>DI is about pushing object creation and wiring as high up in the application as possible, which gives you one central location for the flow of logic. </p>
<p>Code components have dependencies, whether you&#8217;re using Java or Javascript. When your UI widget needs to make a server request to fetch some content, you depend on some code to carry that out. There are usually three approaches.</p>
<p>1. Use a global symbol, such as $.ajax in the world of jQuery.</p>
<p>2. Use a service locator, something like:</p>
<pre class="brush: jscript;">
function updateCustomer(locator) {
  var server = locator.server();
  server.get(&quot;...&quot;);
}
</pre>
<p>Or having the locator being a global variable.</p>
<p>3. Only pass in what you need, like this:</p>
<pre class="brush: jscript;">
function updateCustomer(server) {
  server.get(&quot;...&quot;);
}
</pre>
<p>The first option is the simplest. $.ajax is just a global function that anyone can use. This is also why it&#8217;s the most problematic, because if anyone can use it anywhere, you will end up with no idea of which parts of your application is making Ajax calls. You&#8217;re basically saying &#8220;use any tools you like, I don&#8217;t care&#8221; to your function.</p>
<p>The second alternative passes in a service locator instead, which is better because you have control over what functionality you expose through your locator. It&#8217;s like saying &#8220;here&#8217;s a bag of tools, you can&#8217;t use any other than these, but do what you want with any of these in the bag&#8221;.</p>
<p>The third is the most straight forward. It&#8217;s like saying &#8220;here&#8217;s a screwdriver, it&#8217;s what you&#8217;re gonna use&#8221;. Since we&#8217;re just exposing the server object, there is no risk that other features using other objects will be added to our function. That is a risk with the other two solutions, since they expose more functionality than needed. Another benefit is that it&#8217;s very easy to spot what dependencies your objects have, since they are declared in the constructor. With a locator or with globals, you might have dependencies hidden in large chunks of code that are easy to miss. You are forced to think very hard about how your application is layed out, because it becomes very easy to spot if an object is doing to much, if it requires too many dependencies. You also have to think about how to pass these dependencies around.</p>
<h2>Dependency injection is hard</h2>
<p>So if the third solution is so great, how come most people use the first two? Simply because it&#8217;s hard to achieve. Using a locator is simpler, since you just pack a bag with lots of things and pass it around. But if you use the third option, you have to keep track of who wants the different tools, and make sure that they get them. You also need to make sure that everyone can&#8217;t ask for anything.</p>
<p>In other languages, there are frameworks that help you with these things. Automating object creation in a language like Java or C# is somewhat simple, because you have type hints in the constructors. You can inspect a constructor and find out what it wants. But there is no way to do that in Javascript, since it doesn&#8217;t have types or type hints. Because of this, making a DI container in Javascript is bound to get messy, because you need to define construction rules for all objects. This is problematic because new objects can&#8217;t be added to your application without modifying the wiring code.</p>
<h2>A shot at an automated container in Javascript</h2>
<p>So we now basically know what we need. A container that is semi-smart and can assemble hierarchies of objects. It needs to be able to create objects by convention instead of configuration.<br />
To achieve this, we have a few options. First off, we can cast a constructor to a string which gives us the whole method body and then parse out the argument variable names and use them to map to objects. This is a brittle and error prone idea, since someone might rename a variable and that might take down the entire application. Another option is to add a sort of type hints. Something like this:</p>
<pre class="brush: jscript;">
function Server() {
  return {
    get: function(...) {}
  };
}

function updateCustomer(server) {
  server.get(&quot;...&quot;);
}
updateCustomer.dependencies = [&quot;Server&quot;];
</pre>
<p>It&#8217;s a little unorthodox and perhaps not so Javascripty, but it makes our object more self contained. Our function still isn&#8217;t grabbing Server direcly as with a Service Locator, it&#8217;s merely saying that it would like to get some implementation that behaves like Server does. But it isn&#8217;t very pretty, because the type hints are below the function body, which can be an issue with a more lengthy function. So here&#8217;s some syntactic sugar:</p>
<pre class="brush: jscript;">
var updateCustomer = dependant(
  [&quot;Server&quot;],
  function(server) {
    server.get(&quot;...&quot;);
  }
);
</pre>
<p>The dependant function just maps the function together with the type hints, and it also gives you a simple way to check who has which dependencies. </p>
<p>So now it&#8217;s just a matter of inspecting the dependencies array of a constructor to be able to map it together. Here&#8217;s a proof of concept:</p>
<pre class="brush: jscript;">
var dependant = function(dependencies, func) {
    func.dependencies = dependencies;
    return func;
}

var Container = function() {
    var namespaces;
    var instances;
    var constructors;

    return {
        _init: function() {
            namespaces = [];
            instances = {};
            constructors = {};

            return this;
        },
        addNamespace: function(namespace) {
            namespaces.push(namespace);
        },
        get: function(klass) {
            if(!instances[klass]) {
                if(constructors[klass]) {
                    instances[klass] = constructors[klass]();
                } else {
                    instances[klass] = this.create(klass);
                };
            };
            return instances[klass];
        },
        create: function(klass) {
            for(var i = 0; i &lt; namespaces.length; i++) {
                if(namespaces[i][klass] &amp;&amp; typeof namespaces[i][klass] == &quot;function&quot;) {
                    var constr = namespaces[i][klass];
                    if(constr.dependencies) {
                        var args = [];
                        for(var j = 0; j &lt; constr.dependencies.length; j++) {
                            args.push(this.get(constr.dependencies[j]));
                        };
                        return constr.apply(namespaces[i], args);
                    } else if(constr.length == 0) {
                        return constr();
                    };
                };
            };
            throw &quot;Cannot create '&quot;+ klass +&quot;' because there isn't a registered instance or \
                   constructor, and there was no way to auto wire it.&quot;;
        },
        registerConstructor: function(klass, creator) {
            constructors[klass] = creator;
        },
        registerInstance: function(klass, instance) {
            instances[klass] = instance;
        }
    }._init();
};
</pre>
<p>And some usage code:</p>
<pre class="brush: jscript;">
var ns = {};
ns.Alerter = function() {
    return {
        alert: function() {
            alert(&quot;Mjello!&quot;);
        }
    }
}

ns.MyObject = dependant(
    [&quot;Alerter&quot;],
    function(alerter) {
        return {
            doStuff: function() {
                alerter.alert(&quot;Mjello!&quot;);
            }
        }
    }
);

var cn = Container();
cn.addNamespace(ns);

var o = cn.get(&quot;MyObject&quot;);
o.doStuff();
</pre>
<p>I haven&#8217;t used this type of DI in a Javascript application yet, so I can&#8217;t really say if it&#8217;s any good, but I get a good vibe from it so I&#8217;m planning on using it for a Javascript application that I&#8217;m about to create.</p>
<p>An added benefit here is that the <code>dependencies</code> array can contain anything, not just strings with function names. It could contain CSS selectors to let you decouple DOM access, and maybe even remove the tight coupling with a library such as jQuery or YUI. It could also contain an array of method names, something like:</p>
<pre class="brush: jscript;">
ns.MyObject = dependant(
    [[&quot;alert&quot;]],
    function(alerter) {
        return {
            doStuff: function() {
                alerter.alert(&quot;Mjello!&quot;);
            }
        }
    }
);
</pre>
<p>This says, &#8220;I need one object, and I need it to have an alert method&#8221;, which is basically a flirt with a <a href="http://en.wikipedia.org/wiki/Structural_type_system">structural type system</a> that is a very good fit for Javascript.</p>
<h2>Conclusion</h2>
<p>Javascript is a very open language. You can choose to go OO or procedural, and you can even choose which type of OO you want to use, classical, prototypal or parasitic. It&#8217;s only natural then that there are also a number of different ways to manage dependencies in an application. So when you start a new project in Javascript, you have a smörgåsbord of ways to write code. There&#8217;s no wrong or right, there&#8217;s only what is appropriate for your application. But when you&#8217;ve decided which way to go, stick with it.</p>
]]></content:encoded>
			<wfw:commentRss>http://coffeescripter.com/2010/08/dependency-injection-and-ioc-in-javascript/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Inheritance in Javascript</title>
		<link>http://coffeescripter.com/2010/07/inheritance-in-javascript/</link>
		<comments>http://coffeescripter.com/2010/07/inheritance-in-javascript/#comments</comments>
		<pubDate>Sat, 31 Jul 2010 08:36:10 +0000</pubDate>
		<dc:creator>Andy</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Object Oriented]]></category>

		<guid isPermaLink="false">http://coffeescripter.com/?p=167</guid>
		<description><![CDATA[Javascript is a very dynamic language, and you can implement inheritance and code reuse in multiple ways. Lately, I&#8217;ve grown fond of what Douglas Crockford calls Parasitic Inheritance.
By using parasitic inheritance, you can avoid using the new operator all together. The new operator isn&#8217;t evil, but it&#8217;s problematic in that if you write a function [...]]]></description>
			<content:encoded><![CDATA[<p>Javascript is a very dynamic language, and you can implement inheritance and code reuse in multiple ways. Lately, I&#8217;ve grown fond of what Douglas Crockford calls <a href="http://www.crockford.com/javascript/inheritance.html">Parasitic Inheritance</a>.</p>
<p>By using parasitic inheritance, you can avoid using the new operator all together. The new operator isn&#8217;t evil, but it&#8217;s problematic in that if you write a function and you expect it to be called with the new operator but someone forgets it, wild thing can happen, and it can be really hard to debug. Let&#8217;s take an example:</p>
<pre class="brush: jscript;">
function greet() {
  alert(&quot;Welcome, everyone!&quot;);
}
function Greeter(name) {
  this.name = name;
}
Greeter.prototype.greet = function() {
  alert(&quot;Welcome &quot; + this.name);
}
function Person(name) {
  this.name = name;
  this.greet();
  return this;
}
Person.prototype = new Greeter();
Person.prototype.toString = function() {
  return &quot;I am &quot; + this.name;
}

// Example 1
var name = &quot;Andy&quot;;
var person = new Person(&quot;Coffeescripter&quot;); // alerts &quot;Welcome Coffeescripter&quot;
alert(name); // alerts &quot;Andy&quot;

// Example 2
var name = &quot;Andy&quot;;
var person = Person(&quot;Coffeescripter&quot;); // alerts &quot;Welcome Andy&quot;
alert(name); // alerts &quot;Coffeescripter&quot;
</pre>
<p><em>This way of writing a class and saying that Person inherits from Greeter is rather ugly, so check out John Resigs implementation for some eye candy: <a href="http://ejohn.org/blog/simple-javascript-inheritance/">http://ejohn.org/blog/simple-javascript-inheritance/</a></em></p>
<p>If you&#8217;re not familiar with how <code>this</code> works in Javascript, this may blow your mind. But it&#8217;s perfectly valid code, it&#8217;s just that the <code>this</code> variable points to different places depending on whether you used the new operator or not. When the new operator is used, <code>this</code> points to the new instance that was created. When you&#8217;re not using the new operator, <code>this</code> points to the object that the function was executed in, which in this case was the window object, and that is why <code>this.name = name</code> is overriding the value of the global variable <code>name</code>. This because <code>var name = "Andy";</code> here is technically the same as <code>window.name = "Andy";</code>.</p>
<p>You can&#8217;t tell from inside the function if the new operator was used or not, so you can&#8217;t throw an exception if the new operator was omitted. You could just say that &#8220;all functions that begin with a capital letter should be called with the new operator, or else you&#8217;re stupid&#8221; and be done with it. And while that might be true, you&#8217;re still going to be the one debugging for an hour or so when the new guy who doesn&#8217;t know Javascript that well forgets about the new operator.</p>
<h2>Parasitic Inheritance</h2>
<p>So how about that parasitic inheritance then? It works like this instead:</p>
<pre class="brush: jscript;">
var Greeter = function(name) {
  return {
    greet: function() {
      alert(&quot;Welcome &quot; + name);
    }
  };
};
function Person(name) {
  var obj = Greeter(name);
  obj.greet();
  obj.toString = function() {
    return &quot;I am &quot; + name;
  }
  return obj;
}

// Example 1
var name = &quot;Andy&quot;;
var person = new Person(&quot;Coffeescripter&quot;); // alerts &quot;Welcome Coffeescripter&quot;
alert(name); // alerts &quot;Andy&quot;

// Example 2
var name = &quot;Andy&quot;;
var person = Person(&quot;Coffeescripter&quot;); // alerts &quot;Welcome Coffeescripter&quot;
alert(name); // alerts &quot;Andy&quot;
</pre>
<p>The behaviour is the same if you call Person with the new operator or not. And because of that, it simpler just to forget about the new operator. To me, this code is more straight forward and less magical than the first example, which is always a good thing. One issue people is having with this approach is that for every Person you create, you also create new versions of the greet and toString functions. With the first example, all Person objects share the exact same greet function. That of course means less memory usage, but it also introduces a somewhat scary thought. If all Person objects share the same greet function, what happens when someone decide to replace a persons greet function, it doesn&#8217;t just affect that object, it affects all person objects.</p>
<h2>This trouble with parasitic inheritance</h2>
<p>Something I kept running into with parasitic inheritance was how I didn&#8217;t have access to the created object in the beginning of the function, like this:</p>
<pre class="brush: jscript;">
function Person() {
  var bazooka = Bazooka(this);
  return {
    shoot: function() {
      bazooka.shoot();
    }
  };
}

var Bazooka = function(parent) {
  return {
    shoot: function() {

    }
  }
}
</pre>
<p>Disregarding that we have a cyclic reference here between Person and Bazooka, the problem is that <code>this</code> in <code>var bazooka = Bazooka(this);</code> isn&#8217;t pointing to the person object that we are creating, but the object that the Person function is running in; the window object. So how do we get around this? We could do something like:</p>
<pre class="brush: jscript;">
function Person() {
  var obj = {
    shoot: function() {
      bazooka.shoot();
    }
  };
  var bazooka = Bazooka(obj);
  return obj;
}
</pre>
<p>But that&#8217;s about as pretty and clear as VB&#8217;s let&#8217;s-use-a-variable-with-the-same-name-as-the-function-as-the-return-mechanism-because-function-names-never-change-and-nobody-will-forget-to-update-all-references-to-the-return-variable-when-the-function-is-renamed. So yeah, we can do better. Something like this:</p>
<pre class="brush: jscript;">
function Person() {
  var bazooka;
  return {
    _init: function() {
      bazooka = Bazooka(this);
      return this;
    },
    shoot: function() {
      bazooka.shoot();
    }
  }._init();
}
</pre>
<p>It looks a lot better, and if you&#8217;re used to classical inheritance, you&#8217;re probably used to looking for property declarations at the top, a constructor right after that, and methods down below. If you&#8217;re the suspicious type, you might have noticed that by doing this, we are exposing the <code>_init</code> function to be called again. Which is true, there is nothing stopping you from doing: <code>var p = Person(); p._init();</code> But if this means the end of the world for you, you can always add <code>this._init = undefined;</code> as the first line in the _init function, which makes it impossible to call it twice. </p>
<h3>Privileged functions</h3>
<p>In the first example, there is no way to have a private function that all your public functions can call, not even with John Resigs prettier version. But with parasitic inheritance, it&#8217;s very natural to hide variables and functions through closures, like this:</p>
<pre class="brush: jscript;">
function Person(name) {
  var bazooka;
  var greet = function() {
    alert(&quot;Hi! I'm &quot; + name);
  };
  return {
    _init: function() {
      bazooka = Bazooka(this);
      if(name == &quot;Andy&quot;) {
        greet();
      }
      return this;
    },
    shoot: function() {
      if(name != &quot;Andy&quot;) {
        bazooka.shoot(name);
      }
    }
  }._init();
}
</pre>
<p>Through the closure that the function call to Person creates, both shoot and _init has access to greet, bazooka and name.</p>
<h2>Conclusion</h2>
<p>The key difference between classical and parasitic inheritance is that the classical way is much more focused on an objects type. Change one object, and all other objects of that same type get&#8217;s changes. Parasitic inheritance doesn&#8217;t care about types. It&#8217;s more about assembling functions and properties to create a logical unit. Instead of caring if an argument to your function is of the type Person, you only care about whether or not it has the function greet. There is no right or wrong here, and the two can happily co-exists, but the thing that makes me use parasitic inheritance is how it&#8217;s aligned with the dynamic nature of Javascript. </p>
]]></content:encoded>
			<wfw:commentRss>http://coffeescripter.com/2010/07/inheritance-in-javascript/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Why I still use PHP</title>
		<link>http://coffeescripter.com/2010/07/why-i-still-use-php/</link>
		<comments>http://coffeescripter.com/2010/07/why-i-still-use-php/#comments</comments>
		<pubDate>Mon, 12 Jul 2010 23:47:46 +0000</pubDate>
		<dc:creator>Andy</dc:creator>
				<category><![CDATA[Javascript]]></category>

		<guid isPermaLink="false">http://coffeescripter.com/?p=156</guid>
		<description><![CDATA[Since december 2009, I work in an all Microsoft shop. Coming from a pure LAMP-world &#8211; both Python and PHP &#8211; the step was quite big to C#, VB and SQL Server. But I&#8217;ve grown to really like the technology stack. SQL Server is brilliant much because of SQL Server Management Studio, and I really [...]]]></description>
			<content:encoded><![CDATA[<p>Since december 2009, I work in an all Microsoft shop. Coming from a pure LAMP-world &#8211; both Python and PHP &#8211; the step was quite big to C#, VB and SQL Server. But I&#8217;ve grown to really like the technology stack. SQL Server is brilliant much because of SQL Server Management Studio, and I really wish there were a client for MySQL that&#8217;s as good as Management Studio. C# is really nice mostly thanks to Visual Studio, which is probably the best IDE there is. And with ASP.NET MVC, Microsoft has a really nice platform for web development. They have borrowed almost all of the best ideas from other successful frameworks like Rails, Django, etc.</p>
<p>But even with ASP.NET MVC, and Django, I still come back to doing web development in PHP in the projects I do on my spare time. And the reason is definitely not language elegance, but it&#8217;s very much because of the framework/library <a href="http://konstrukt.dk">Konstrukt</a>.</p>
<p>Most of the other MVC-ish frameworks out there use the idiom of &#8220;/controller/action/id/some/other/parameter&#8221;, and it just doesn&#8217;t feel right. It feels right in simple cases like &#8220;/users&#8221; and &#8220;/users/12&#8243;. But what about &#8220;/users/edit/12&#8243;? The url should &#8211; if you ask me &#8211; be hierarchical, and it should always be possible to remove the last url segment, and still get a logical response. But if you remove 12 from &#8220;/users/edit/12&#8243;, what do you get? A bunch of forms, so you can edit all users at the same time?</p>
<p>Instead, Konstrukt handles this by using hierarchical controllers/components. So instead of mapping a request to one specific controller, one controller handles each url segment. So if you have a url like &#8220;/users/12/comments&#8221;, you&#8217;d start of by having the root controller handle the &#8220;/&#8221; part. That controller sees that the whole url isn&#8217;t just &#8220;/&#8221;, so that controller is responsible for mapping forward to another controller, to handle the &#8220;users&#8221; segment. That controller also sees that there&#8217;s more in the url, and maps forward to a controller that handles &#8220;12&#8243;, and then &#8211; last but not least &#8211; the controller that handles the &#8220;comments&#8221; part. That controller sees that it&#8217;s the last part, so it&#8217;s responsible for rendering the result. You might think that ends up being an awful lot of controllers, and it sure does, since one controller basically does just one thing. But that&#8217;s a good thing. Instead of having a User-controller with Add, Remove, List, Edit-actions. It also lets you reuse controllers very elegantly. You might have both &#8220;/comments&#8221;, and &#8220;/users/12/comments&#8221;, for which you can reuse the same controller. Each controller has access to it&#8217;s parent controller, so the controller can use it&#8217;s parent as a way to filter out comments per user, or display all comments.</p>
<p>I know that I can use routing in most other frameworks to get almost the right result, but it just ends up feeling like I&#8217;m wedging it in, it&#8217;s not as elegant as with Konstrukt, mostly because of the &#8220;one controller with many action methods&#8221; thing.</p>
<p>This, together with having control over controller creation which allows you to use a DI container to create them, together with excellent support for different content types, together with the fact that it&#8217;s very (almost extremely) loosely coupled, makes me love PHP. I like PHP, but Konstrukt makes me love it. If I start a new web project in Python or C#, I start of with a great feeling of how elegant those languages are, but I always end up really missing PHP because of Konstrukts elegance. If I could just find the time to port Konstrukt to C# and Python&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://coffeescripter.com/2010/07/why-i-still-use-php/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Separate concerns with queues</title>
		<link>http://coffeescripter.com/2009/08/separate-concerns-with-queues/</link>
		<comments>http://coffeescripter.com/2009/08/separate-concerns-with-queues/#comments</comments>
		<pubDate>Thu, 20 Aug 2009 18:00:11 +0000</pubDate>
		<dc:creator>Andy</dc:creator>
				<category><![CDATA[Javascript]]></category>

		<guid isPermaLink="false">http://coffeescripter.com/?p=143</guid>
		<description><![CDATA[When you&#8217;re doing Javascript, you often find yourself listening to events, and then taking action upon what happened. Let&#8217;s take a classic example; the drag and drop effect. You have code that listens for the mousedown event which should signal that it&#8217;s time to start listening for the mousemove event. In the mousemove event listener [...]]]></description>
			<content:encoded><![CDATA[<p>When you&#8217;re doing Javascript, you often find yourself listening to events, and then taking action upon what happened. Let&#8217;s take a classic example; the drag and drop effect. You have code that listens for the mousedown event which should signal that it&#8217;s time to start listening for the mousemove event. In the mousemove event listener code, you probably have code to calculate positions, check if the drag is within boundaries, etc. And then code to actually move the element so the drag effect can be achieved. Something like this in psuedo code:</p>
<pre class="brush: jscript;">
function onMousedown(e) {
  initDrag(e);
}
function initDrag(e) {
  document.onmousemove = onMousemove;
}
function onMousemove(e) {
  element.style.top = e.pageY +'px';
  element.style.left = e.pageX +'px';
}
</pre>
<p>But I would suggest that the code to reposition the element should be moved away from the event listener. Not just moving that code into it&#8217;s own function, and let the event listener call that function (even though that&#8217;s a good thought). Instead, let&#8217;s create a queue:</p>
<pre class="brush: jscript;">
function onMousedown(e) {
  initDrag(e);
}
function initDrag(e) {
  document.onmousemove = onMousemove;
}
var new_positions = [];
function onMousemove(e) {
  new_positions.push({top: e.pageY, left: e.pageX});
}
</pre>
<p>And then code to process the queue:</p>
<pre class="brush: jscript;">
var paint_interval = setInterval(
  function() {
    if(new_positions.length) {
      var pos = new_positions.shift();
      element.style.top = pos.top +'px';
      element.style.left = pos.left +'px';
    }
  },
  50
);
</pre>
<p>So what&#8217;s the use of this? Doesn&#8217;t it just add unnecessary complexity? In this very simple example it sure does, but there&#8217;s still a beauty in it since we are separating concerns. On one side, there&#8217;s code that listens to what the user wants to happen, and adds that to the queue. On the other side, there&#8217;s code that decides whether to actually listen to what the user wants to do, or to deny it, and the two sides doesn&#8217;t need to know about the other.<br />
You could add logic in the queue processing function (the function in the interval) that checks if the queue is too large, and then ignore the first 10 queue items and move directly to number 11, which would save the browser having to paint those 10 steps and move directly to number 11.<br />
Another reason could be that you only want to allow the element to move X number of pixels per run, regardless of how fast the user drags, and then eventually catch up with the mouse position. Or if you have a lot of stuff going on, and you don&#8217;t care if the dragging is smooth, you can change the interval to run 5 times per second, instead of 20.</p>
<p>This is essentially the <a href="http://en.wikipedia.org/wiki/Command_pattern">Command Pattern</a>, except that a Command is executable in itself, and my queue items are just data holders, and it&#8217;s up to the queue processor to make sense of that data. The Command pattern is more general, as any command can be added to the queue/stack, and thesehere queues are more specialized, since all queue items are of the same type.</p>
<p>So the point is to separate logic, and decouple different parts of your application to make them more isolated. The queue processing doesn&#8217;t care where a queue item comes from, it&#8217;s only concern is to process the queue. That enables you to add queue items from other parts of the application as well, and the code that listens to mousemove events doesn&#8217;t need to be touched.<br />
That enables you to let your application grow and meet new requirements without making a mess of the code with lots if nested if statements, since you have separated logic. If nothing else, you can impress other people by telling them about your fancy queue processing architecture. It probably won&#8217;t impress beautiful women at your local bar though.</p>
]]></content:encoded>
			<wfw:commentRss>http://coffeescripter.com/2009/08/separate-concerns-with-queues/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A Javascript OO gotcha</title>
		<link>http://coffeescripter.com/2009/08/a-javascript-oo-gotcha/</link>
		<comments>http://coffeescripter.com/2009/08/a-javascript-oo-gotcha/#comments</comments>
		<pubDate>Thu, 13 Aug 2009 18:01:57 +0000</pubDate>
		<dc:creator>Andy</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Object Oriented]]></category>

		<guid isPermaLink="false">http://coffeescripter.com/?p=138</guid>
		<description><![CDATA[Every now and then I run into this issue when I&#8217;m do OO in Javascript. It creates really wierd bugs that can make you want to rip you hair off (I have no hair left&#8230;), so I thought it might be a good idea to share it. It all boils down to the fact that [...]]]></description>
			<content:encoded><![CDATA[<p>Every now and then I run into this issue when I&#8217;m do OO in Javascript. It creates really wierd bugs that can make you want to rip you hair off (I have no hair left&#8230;), so I thought it might be a good idea to share it. It all boils down to the fact that objects in Javascript are references by default.</p>
<p>So let&#8217;s say you have code like this:</p>
<pre class="brush: jscript;">
var User = Class.extend({
  _friends: [],
  _name: '',
  init: function(name) {
    this._name = name;
  },
  name: function() {
    return this._name;
  },
  addFriend: function(friend) {
    this._friends.push(friend);
  },
  greetFriends: function() {
    alert('Hi '+ this._friends.join(', ') +'!');
  }
});

var fred = new User('Fred');
var mike = new User('Mike');
var jennifer = new User('Jennifer');
var sara = new User('Sara');

fred.addFriend(jennifer.name());
fred.addFriend(sara.name());

mike.greetFriends();
</pre>
<p>You would expect that Mike who nobody seems to like would just alert &#8220;Hi !&#8221;, but he alerts Freds friends as well. And that&#8217;s because objects in Javascript (arrays are objects as well) are passed by reference. So all of Freds friends also become Mikes friends, since they share the same friend array.</p>
<p>So to get away from this, the trick is to declare your properties in the constructor, like this:</p>
<pre class="brush: jscript;">
var User = Class.extend({
  _friends: [],
  _name: '',
  init: function(name) {
    this._name = name;
    this._friends = [];
  },
  name: function() {
    return this._name;
  },
  addFriend: function(friend) {
    this._friends.push(friend);
  },
  greetFriends: function() {
    alert('Hi '+ this._friends.join(', ') +'!');
  }
});
</pre>
<p>Since the constructor (init) is called every time a new user object is created, the friends array is set for only that instance. But sometimes you might forget to reset the variable in the constructor, so I usually do this:</p>
<pre class="brush: jscript;">
var User = Class.extend({
  _friends: false,
  _name: '',
  init: function(name) {
    this._name = name;
    this._friends = [];
  },
  name: function() {
    return this._name;
  },
  addFriend: function(friend) {
    this._friends.push(friend);
  },
  greetFriends: function() {
    alert('Hi '+ this._friends.join(', ') +'!');
  }
});
</pre>
<p>Just to make sure that there&#8217;s no risk of a shared array. You might even skip the declaration at the top, but I&#8217;m used to looking there for property declarations, so I set them at the top. </p>
<p>I&#8217;m sure that you already thought about this by know, but this feature in Javascript makes it possible to have &#8220;static&#8221; properties that are shared between all instances of the same class. I would advise you to use such a strategy sparsely though, as it&#8217;s not very obvious that it&#8217;s a shared variable. But the good thing about it is that this Javascript version of static properties doesn&#8217;t suffer the same problems that statics do in Java/PHP, since the static can be turned into a local just by resetting it in the constructor, without it affecting other objects. Something like:</p>
<pre class="brush: jscript;">
var User = Class.extend({
  _friends: [],
  _name: '',
  init: function(name, share_friends) {
    this._name = name;
    if(!share_friends) {
      this._friends = [];
    }
  },
  name: function() {
    return this._name;
  },
  addFriend: function(friend) {
    this._friends.push(friend);
  },
  greetFriends: function() {
    alert('Hi '+ this._friends.join(', ') +'!');
  }
});

var fred = new User('Fred', true);
var mike = new User('Mike', false);
var jennifer = new User('Jennifer', true);
var sara = new User('Sara', true);

fred.addFriend(jennifer.name());
fred.addFriend(sara.name());
mike.addFriend(fred.name());

mike.greetFriends();
sara.greetFriends();
</pre>
<p>This code now tells us that Mike only has Fred as a friend, whereas Sara shares friends with Fred, and has both herself and Jennifer as her friends.</p>
<p>Happy coding!</p>
]]></content:encoded>
			<wfw:commentRss>http://coffeescripter.com/2009/08/a-javascript-oo-gotcha/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>AD Gallery &#8211; a jQuery gallery plugin</title>
		<link>http://coffeescripter.com/2009/07/ad-gallery-a-jquery-gallery-plugin/</link>
		<comments>http://coffeescripter.com/2009/07/ad-gallery-a-jquery-gallery-plugin/#comments</comments>
		<pubDate>Thu, 09 Jul 2009 14:04:30 +0000</pubDate>
		<dc:creator>Andy</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://coffeescripter.com/?p=122</guid>
		<description><![CDATA[I got inspired by myself when I wrote the Editable Select plugin, so I decided to write another one. It&#8217;s a gallery plugin that&#8217;s a bit different than plugins like Thickbox and Lightbox.
You can see it here (it&#8217;s a work in progress, please be gentle).
After quite a lot of tweaking, bug fixing and making sure [...]]]></description>
			<content:encoded><![CDATA[<p>I got inspired by myself when I wrote the <a href="http://coffeescripter.com/2009/07/an-editable-select-list-plugin-for-jquery/">Editable Select</a> plugin, so I decided to write another one. It&#8217;s a gallery plugin that&#8217;s a bit different than plugins like Thickbox and Lightbox.</p>
<p>You can see it <a href="http://coffeescripter.com/code/ad-gallery/">here</a> (it&#8217;s a work in progress, please be gentle).</p>
<p>After quite a lot of tweaking, bug fixing and making sure it works in popular browsers, I&#8217;ve now released version 1.0.0. If you find any bugs, or have any features you&#8217;d want for it, please don&#8217;t hesitate to send a comment here.</p>
<p>Happy coding!</p>
]]></content:encoded>
			<wfw:commentRss>http://coffeescripter.com/2009/07/ad-gallery-a-jquery-gallery-plugin/feed/</wfw:commentRss>
		<slash:comments>371</slash:comments>
		</item>
		<item>
		<title>An editable select list plugin for jQuery</title>
		<link>http://coffeescripter.com/2009/07/an-editable-select-list-plugin-for-jquery/</link>
		<comments>http://coffeescripter.com/2009/07/an-editable-select-list-plugin-for-jquery/#comments</comments>
		<pubDate>Tue, 07 Jul 2009 07:33:56 +0000</pubDate>
		<dc:creator>Andy</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://coffeescripter.com/?p=114</guid>
		<description><![CDATA[For a job I did for a client for a couple of months ago, there was a need for a select list that could be editable. I found a plugin for it (don&#8217;t remember where I found it, unfortunately), and it worked, kinda. So this morning, I felt like writing such a plugin from scratch.
It [...]]]></description>
			<content:encoded><![CDATA[<p>For a job I did for a client for a couple of months ago, there was a need for a select list that could be editable. I found a plugin for it (don&#8217;t remember where I found it, unfortunately), and it worked, kinda. So this morning, I felt like writing such a plugin from scratch.</p>
<p>It basically takes the best of an input field, and a select box/list, and mixes it together. It takes a real select list and transforms it to an input field with options, and mimics most (if not even more) of the features of a real select box. Since it&#8217;s a real select list from the start, it degrades nicely for those without Javascript.</p>
<p>You can find the code and an example here:<br />
<a href="http://coffeescripter.com/code/editable-select/" target="_blank">http://coffeescripter.com/code/editable-select/</a></p>
]]></content:encoded>
			<wfw:commentRss>http://coffeescripter.com/2009/07/an-editable-select-list-plugin-for-jquery/feed/</wfw:commentRss>
		<slash:comments>29</slash:comments>
		</item>
		<item>
		<title>Closures in Javascript</title>
		<link>http://coffeescripter.com/2009/07/closures-in-javascript/</link>
		<comments>http://coffeescripter.com/2009/07/closures-in-javascript/#comments</comments>
		<pubDate>Sat, 04 Jul 2009 11:45:57 +0000</pubDate>
		<dc:creator>Andy</dc:creator>
				<category><![CDATA[Javascript]]></category>

		<guid isPermaLink="false">http://coffeescripter.com/?p=93</guid>
		<description><![CDATA[Closures in Javascript are very powerful, and without them, you wouldn&#8217;t really be able to do very much in Javascript. They can be defined as in Wikipedias post about closures:
In some languages, a closure may occur when a function is defined within another function, and the inner function refers to local variables of the outer [...]]]></description>
			<content:encoded><![CDATA[<p>Closures in Javascript are very powerful, and without them, you wouldn&#8217;t really be able to do very much in Javascript. They can be defined as in Wikipedias post about closures:</p>
<blockquote><p>In some languages, a closure may occur when a function is defined within another function, and the inner function refers to local variables of the outer function. At runtime, when the outer function executes, a closure is formed, consisting of the inner function’s code and references to any variables of the outer function required by the closure; such variables are called the upvalues of the closure.</p></blockquote>
<p>That can be a bit of a dry explaination, so here&#8217;s an example.</p>
<pre class="brush: jscript;">
function testClosure() {
  var foo = 'bar';
  return function() {
    alert(foo);
  }
}
var callback = testClosure();
callback();
</pre>
<p>This code will alert &#8220;bar&#8221;, even though there&#8217;s no &#8220;foo&#8221; variable in the anonymous function that testClosure returns. This is because the anonymous function we have created has access to its parent scope (that is, a closure has been created when the testClosure function executes). So when we alert the foo variable, Javascript will check for a variable called foo in the current function scope, and it won&#8217;t find it. Then it goes up to the parent scope, the scope of testClosure. It finds a variable called foo there, so that&#8217;s the variable that will be used. And you&#8217;ve probably seen this, perhaps without realizing that it&#8217;s a closure. Here&#8217;s some more explainatory code:</p>
<pre class="brush: jscript;">
function testClosure() {
  var foo = 'bar';
  var fn = function() {
    var foo = 'baz';
    alert(foo);
  };
  alert(foo);
  return fn;
}
var callback = testClosure();
callback();
</pre>
<p>Instead of just alerting &#8220;bar&#8221;, this will alert &#8220;baz&#8221; as well as &#8220;bar&#8221;, since there&#8217;s a variable &#8220;foo&#8221; in the inner function, and the testClosure also alerts the foo variable. So here&#8217;s a gotcha for you:</p>
<pre class="brush: jscript;">
function initEvents() {
  for(var i = 1; i &lt;= 5; i++) {
    var element = document.getElementById('element'+ i);
    element.onclick = function() {
      alert(i);
    }
  }
}
</pre>
<p>One might hope that this code will result in alerting &#8220;3&#8243; when you click on the element with the id &#8220;element3&#8243;, but it doesn&#8217;t. It alerts &#8220;6&#8243; for all elements. And that&#8217;s because the value i is set to 6 in the last cycle of the loop. So by the time the element is clicked, the variable i will have the value of 6. The further prove the point, look at this code.</p>
<pre class="brush: jscript;">
function initEvents() {
  for(var i = 1; i &lt;= 5; i++) {
    var element = document.getElementById('element'+ i);
    element.onclick = function() {
      alert(i);
    }
  }
  i = 'foo';
}
</pre>
<p>Now all element clicks will alert &#8220;foo&#8221;. So how would we solve this, because we need the current value of i in the click event. There are of course more than one way to solve this, but in the context of closures, this is how we can solve it.</p>
<pre class="brush: jscript;">
function initEvents() {
  for(var i = 1; i &lt;= 5; i++) {
    bindEvent(i);
  }
}
function bindEvent(i) {
  var element = document.getElementById('element'+ i);
  element.onclick = function() {
    alert(i);
  }
}
</pre>
<p>Now that we&#8217;ve moved the event binding code to another function, we&#8217;re no longer bound by the latest value of i in initEvents. The value of i is passed to the bindEvent function. We&#8217;re still creating closures though. Everytime bindEvent is called, a closure is created between bindEvent and the onclick handler function. But since bindEvent is called five times, five closures are created, and every closure has a different value for i. This was not the case in the first example, because there was only one function call, thus only one closure was created, and there was only one value for i.</p>
<p>Now, closures aren&#8217;t just between a function and it&#8217;s direct parent scope only. The closure recurses up the tree, like in this code.</p>
<pre class="brush: jscript;">
function topLevel() {
  var root = 'root';
  function level1() {
    function level2() {
      function level3() {
        alert(root);
      }
      level3();
    }
    level2();
  }
  level1();
}
topLevel();
</pre>
<p>When the level3 function tries to access the foo variable, Javascript looks for it in level2&#8217;s scope, then in level1, and then it finally finds it in topLevel. </p>
<p>A word of caution though. Since closures lets different functions share variables, you can accidentally override a variable in a function, and that will affect other functions that also has a reference to that variable. Something like:</p>
<pre class="brush: jscript;">window.onload = function() {
  var foo = 'bar';
  for(var i = 1; i &lt;= 5; i++) {
    var element = document.getElementById('element'+ i);
    element.onclick = function() {
      foo += ' clicked! ';
      alert(foo);
    }
  }
}
</pre>
<p>For everytime you click one of those elements, the foo variable is changed, even if you click on different elements.</p>
<h2>Using closures in OO Javascript</h2>
<p>When you&#8217;re writing OO in Javascript, you really, really need closures. For these examples, I&#8217;m using John Resigs<br />
<a href="http://ejohn.org/blog/simple-javascript-inheritance/">Simple Javascript Inheritance</a>.</p>
<p>So you have a User class, perhaps, like this.</p>
<pre class="brush: jscript;">
var User = Class.extend({
  name: 'Andy',
  init: function() {
    var context = this;
    document.getElementById('show_name').onclick = function() {
      alert(context.getName());
    }
  },
  getName: function() {
    return this.name;
  }
});
</pre>
<p>Since &#8220;this&#8221; will have special meaning inside the onclick handler function, we define a &#8220;context&#8221; variable that holds the reference to the User object, and that will be available in the onclick handler thanks to the closure that is created. Some prefer to name that variable &#8220;self&#8221;, but I prefer &#8220;context&#8221;, since that&#8217;s really what it is, the handlers context.</p>
<p>So this enables you to access the User object inside the handler function without having to set the User object as a property on the DOM element, like this.</p>
<pre class="brush: jscript;">
var User = Class.extend({
  name: 'Andy',
  init: function() {
    var element = document.getElementById('show_name');
    element.User = this;
    element.onclick = function() {
      alert(this.User.getName());
    }
  },
  getName: function() {
    return this.name;
  }
});
</pre>
]]></content:encoded>
			<wfw:commentRss>http://coffeescripter.com/2009/07/closures-in-javascript/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>The beauty of this</title>
		<link>http://coffeescripter.com/2009/07/the-beauty-of-this/</link>
		<comments>http://coffeescripter.com/2009/07/the-beauty-of-this/#comments</comments>
		<pubDate>Sat, 04 Jul 2009 09:53:09 +0000</pubDate>
		<dc:creator>Andy</dc:creator>
				<category><![CDATA[Javascript]]></category>

		<guid isPermaLink="false">http://coffeescripter.com/?p=63</guid>
		<description><![CDATA[I&#8217;d argue that you won&#8217;t love Javascript until you know about the &#8220;this&#8221; reference, and how to work with it. If you&#8217;ve done object oriented programming, you&#8217;re probably familiar with the &#8220;this&#8221; reference in some other language. But if you&#8217;re thinking that it works the same in Javascript as in your language of choice, you&#8217;re [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;d argue that you won&#8217;t love Javascript until you know about the &#8220;this&#8221; reference, and how to work with it. If you&#8217;ve done object oriented programming, you&#8217;re probably familiar with the &#8220;this&#8221; reference in some other language. But if you&#8217;re thinking that it works the same in Javascript as in your language of choice, you&#8217;re probably wrong, and you&#8217;re in for a wonderful surprise. Let&#8217;s start with a basic examle.</p>
<pre class="brush: jscript;">
function thisTest() {
  alert(this);
}
thisTest();
</pre>
<p>This will alert &#8220;[object Window]&#8220;. That&#8217;s because the thisTest function is a global function, and all global variables are assigned to the window object. So the code above is the same as:</p>
<pre class="brush: jscript;">
window.thisTest = function() {
  alert(this);
}
window.thisTest();
</pre>
<p>The only difference is that in the latter example, our function is an anonymous function that is assigned to a variable, and the first one is a <a href="http://yura.thinkweb2.com/named-function-expressions/" target="_blank">named function</a>. </p>
<p>So now that we know that a global function is assigned to the window object, we can take it a step further. Take this code:</p>
<pre class="brush: jscript;">
var color = 'red';
function tellColor() {
  alert(color);
}
</pre>
<p>It can be written like this instead:</p>
<pre class="brush: jscript;">
window.color = 'red';
function tellColor() {
  alert(window.color);
}
</pre>
<p>This is better, because we clearly state that it&#8217;s a global variable we&#8217;re using. Since you should be very careful about using global variables, we want it to be very obvious in the code that the variable is global. But we take it even a step further, by doing:</p>
<pre class="brush: jscript;">
window.color = 'red';
function tellColor() {
  alert(this.color);
}
</pre>
<p>So why is this better, you might wonder? Because we&#8217;re not explicitly using a global variable, and here&#8217;s why:</p>
<pre class="brush: jscript;">
window.color = 'red';
window.tellColor = function() {
  alert(this.color);
}

var other_colors = {};
// Could also be var other_colors = new Object();
other_colors.color = 'green';
other_colors.tellColor = window.tellColor;
other_colors.tellColor();
</pre>
<p>This code will alert &#8220;green&#8221;, because of how Javascripts &#8220;this&#8221; reference work. So let&#8217;s go through the code. First, we define an object, &#8220;other_colors&#8221;. Then we assign the color property to that object, and then we assign the function. Now that part may be a bit strange, since we&#8217;re working with a function without calling it, we&#8217;re passing it around. This works because everything in Javascript is an object, even functions. And we can pass objects around, and assign them to variables, which is just what we&#8217;re doing here.</p>
<p>And when were assigning other_colors.tellColor to window.tellColor, it&#8217;s still the same function, but the &#8220;this&#8221; reference points to different objects in other_colors.tellColor and window.tellColor.</p>
<p>This allows you to write highly reusable code, since you can use the exact same function, but assign it to different objects and get different results. So if you&#8217;re familiar with the concept of inheritance, mixins and traits in OO, you can see how you can implement it in Javascript, it&#8217;s basically just copying function pointers from one object to another.</p>
<h2>Iterating over this</h2>
<p>Since everything in Javascript is an object, basically everything can be iterated over, and especially the &#8220;this&#8221; reference. Like this:</p>
<pre class="brush: jscript;">
// Just a simple namespace
var ns = {};
ns.foo = 'bar';
ns.baz = 'foo';
ns.iterator = function() {
  for(var k in this) {
    alert(k +' =&gt; '+ this[k];
  }
}
ns.iterator();
</pre>
<p>This code will alert:</p>
<pre>
foo => bar
baz => boo
iterator => function() {
  for(var k in this) {
    alert(k +' => '+ this[k];
  }
}
</pre>
<p>Because of how Javascript works, you can access object properties both with <code>object.property</code>, and <code>object['property']</code>. So this code will iterate over all properties in the object which the iterator function is attached to and alert the property name and the property value, even our iterator function gets alerted. </p>
<p>To really get the best from Javascript, you should also <a href="http://coffeescripter.com/2009/07/closures-in-javascript/">read up on how closures work</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://coffeescripter.com/2009/07/the-beauty-of-this/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Building a Javascript clone of Civilization, part 1</title>
		<link>http://coffeescripter.com/2009/07/building-a-javascript-clone-of-civilization-part-1/</link>
		<comments>http://coffeescripter.com/2009/07/building-a-javascript-clone-of-civilization-part-1/#comments</comments>
		<pubDate>Thu, 02 Jul 2009 07:08:28 +0000</pubDate>
		<dc:creator>Andy</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Object Oriented]]></category>

		<guid isPermaLink="false">http://coffeescripter.com/?p=45</guid>
		<description><![CDATA[So I thought it might be fun to build a game in Javascript, and not just some dead simple game. As I was younger (because I&#8217;m so old now) I liked the games Civilization and Colonization a lot, so I wanted to try to make a clone of them, using Javascript.
I decided from the start [...]]]></description>
			<content:encoded><![CDATA[<p>So I thought it might be fun to build a game in Javascript, and not just some dead simple game. As I was younger (because I&#8217;m so old now) I liked the games Civilization and Colonization a lot, so I wanted to try to make a clone of them, using Javascript.</p>
<p>I decided from the start that I wanted to use jQuery, and Object Oriented Javascript. To mimic OO inheritance, I once again used John Resigs <a href="http://ejohn.org/blog/simple-javascript-inheritance/">Simple Javascript Inheritance</a>.</p>
<p>So the first thing to do was to model the entities I needed in the game. I started out with the obvious one, the Unit class. Added a few methods to it, and moved on to the Map class, because I wanted to get something at least partially working very fast. So I made a Map class that generated a map of tiles that could hold units. I greated a Tile class, and the Map class would hold all instances to the tiles. A tile has a &#8220;height&#8221; property, which defines the altitude of it (1 is deep water, 6 is low land, and 10 is oh-my-god-that&#8217;s-high-mountains). For now, I&#8217;m just randomizing the heights of the generated tiles, but that doesn&#8217;t make a very realistic map, so that&#8217;s on my TODO-list.</p>
<p>To get something working, I needed a way to connect unit to tiles. At first, I thought about letting the Unit hold an instance to the Tile it was on, but soon realized that it wouldn&#8217;t be a good idea. Instead, I created a UnitLocations class, which holds all units and all tiles, and connects them. </p>
<p>I also needed to be sure that units can&#8217;t move over the map as they like, land units can move over water (except the JesusUnit, which will be covered in part 23 of this series). So I created a LandUnit, and a WaterUnit, derived from the Unit base class. For now, when you try to move a unit, the <code>game.Tile::canTake(game.Unit unit)</code> method is queried to see if the unit can be moved to that tile. I&#8217;m pretty sure I have to move that logic to somewhere else at a later stage, but it&#8217;s good enough for now.</p>
<p>So I had a map, and I had a couple of units on it, that could move around. Then I remembered that Civilization is turn based. And my ambition is to let players play against each other over the series of tubes that we call the Internets. But sitting and waiting for other players to make their move can be tiring at best, so I needed another solution. Instead, i decided that Units has a &#8220;move_points&#8221;. Let&#8217;s say that LandUnit has 3 move_points, and moves over three tiles. Then move_points becomes zero, and that unit has to rest for a couple of seconds before it can move again. Right now, it&#8217;s accomplished by an interval running in every unit that adds move_points every two seconds. Each unit type also has a &#8220;max_move_points&#8221; property, so you wouldn&#8217;t be able to move the unit over a gazillion tiles if you waited long enough.</p>
<p>So I was quite excited about this, and wanted to move on and make more features. But then I stopped and thought some more about it, and realized that I need an event architecture to move on. And I hear you, Javascript already has events, and jQuery allows you to trigger custom events that you define on your own, but I wasn&#8217;t quite satisfied with how that worked. So I&#8217;m going to get cracking on a way to define and trigger my own events, and that will be part 2 of this series.</p>
<p>You can find the game here for now: <a href="http://dev.online.nu/game/" target="_blank">http://dev.online.nu/game/</a>.<br />
When you want to move a unit (a unit is one of those pretty red squares), just click on it, then move it by using your keyboard arrows.</p>
<p>Til then, happy coding!</p>
]]></content:encoded>
			<wfw:commentRss>http://coffeescripter.com/2009/07/building-a-javascript-clone-of-civilization-part-1/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
