<?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</title>
	<atom:link href="http://coffeescripter.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://coffeescripter.com</link>
	<description>Just another developer blog</description>
	<lastBuildDate>Thu, 20 Aug 2009 19:28:19 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<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: javascript;">
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: javascript;">
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: javascript;">
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: javascript;">
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: javascript;">
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: javascript;">
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: javascript;">
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>161</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>16</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: javascript;">
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: javascript;">
function testClosure() {
  var foo = 'bar';
  return function() {
    var foo = 'baz';
    alert(foo);
  }
  alert(foo);
}
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: javascript;">
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: javascript;">
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: javascript;">
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: javascript;">
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: javascript;">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: javascript;">
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: javascript;">
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>0</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: javascript;">
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: javascript;">
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: javascript;">
var color = 'red';
function tellColor() {
  alert(color);
}
</pre>
<p>It can be written like this instead:</p>
<pre class="brush: javascript;">
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: javascript;">
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: javascript;">
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: javascript;">
// 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>1</slash:comments>
		</item>
		<item>
		<title>Automatic getters and setters in Javascript</title>
		<link>http://coffeescripter.com/2009/07/automatic-getters-and-setters-in-javascript/</link>
		<comments>http://coffeescripter.com/2009/07/automatic-getters-and-setters-in-javascript/#comments</comments>
		<pubDate>Wed, 01 Jul 2009 18:18:48 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Object Oriented]]></category>

		<guid isPermaLink="false">http://coffeescripter.com/?p=1</guid>
		<description><![CDATA[When you&#8217;re working with object oriented code, writing those dumb getters and setters can be a bit of a pain, since they&#8217;re just getting and setting simple values most of the times. So I thought I&#8217;d bring in some magic to my Javascript classes to generate these methods.
I&#8217;m using John Resigs Simple Javascript Inheritance to [...]]]></description>
			<content:encoded><![CDATA[<p>When you&#8217;re working with object oriented code, writing those dumb getters and setters can be a bit of a pain, since they&#8217;re just getting and setting simple values most of the times. So I thought I&#8217;d bring in some magic to my Javascript classes to generate these methods.</p>
<p>I&#8217;m using John Resigs <a href="http://ejohn.org/blog/simple-javascript-inheritance/">Simple Javascript Inheritance</a> to emulate class inheritance in Javascript, so you might want to check that out.</p>
<p>So the first step is to create a base class that takes care of the getters and setters for us.</p>
<pre class="brush: javascript;">
var DomainObject = Class.extend({
  init: function() {
    /**
     * Generating getters and setters for the domain object by looping over
     * all properties that start with _ and automatically creating getters/setters
     * If the property is &quot;_first_name&quot;, the getter will become &quot;firstName()&quot;, and
     * the setter will become &quot;setFirstName()&quot;
     */
    for(var key in this) {
      createGettersAndSetters(key, this);
    }
    function camelize(str) {
      var ret = '';
      for(var i = 0; i &lt; str.length; i++) {
        var chr = str.charAt(i);
        if(chr != '_') {
          ret += chr;
        } else {
          i++;
          ret += str.charAt(i).toUpperCase();
        }
      }
      return ret;
    }
    function createGettersAndSetters(key, context) {
      if(key.indexOf('_') === 0 &amp;&amp; typeof context[key] != 'function') {
        var set_method = 'set'+ camelize(key);
        // Make sure we don't override an existing setter
        if(!context[set_method]) {
          context[set_method] = function(value) {
            context[key] = value;
          }
        }
        // Using substr to remove the starting _, since we don't want the
        // string to start with a capital letter, as we do with the setters
        var get_method = camelize(key.substr(1));
        // Make sure we don't override an existing getter
        if(!context[get_method]) {
          context[get_method] = function() {
            return context[key];
          }
        }
      }
    }
  }
});
</pre>
<p>So now that we&#8217;ve got our class that handles the magic, we need to test it!</p>
<pre class="brush: javascript;">
var User = DomainObject.extend({
  _id: false,
  _name: '',
  setId: function(id) {
    if(validUserId(id) {
      this._id = id;
    }
  },
  sayHello: function() {
    alert('Hi! My name is '+ this.name());
  }
});

var usr = new User();
usr.setName('Anders');
// Will alert &quot;Hi! My name is Anders&quot;
usr.sayHello();
</pre>
<p>So what is does is that it takes all properties of the &#8220;class&#8221; that begins with an underscore, and generates getters and setters for them, if a getter/setter isn&#8217;t already defined. The format for the methods are setProperty() and property(), so if you have a property called &#8220;_first_name&#8221;, the setter becomes &#8220;setFirstName&#8221;, and the getter becomes &#8220;firstName&#8221;.</p>
<p>Happy coding! </p>
]]></content:encoded>
			<wfw:commentRss>http://coffeescripter.com/2009/07/automatic-getters-and-setters-in-javascript/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
