<?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>Wed, 02 May 2012 08:00:24 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Embedding Javascript in .NET</title>
		<link>http://coffeescripter.com/2012/05/embedding-javascript-in-net/</link>
		<comments>http://coffeescripter.com/2012/05/embedding-javascript-in-net/#comments</comments>
		<pubDate>Wed, 02 May 2012 07:52:03 +0000</pubDate>
		<dc:creator>Andy</dc:creator>
				<category><![CDATA[Javascript]]></category>

		<guid isPermaLink="false">http://coffeescripter.com/?p=307</guid>
		<description><![CDATA[We have a C++/C# based application where I work, and we currently use VBScript as a scripting language. Needless to say, we want to replace it, and we&#8217;ve decided that Javascript is a good candidate. When it comes to executing Javascript in .NET, there are quite a few options. We have narrowed it down to [...]]]></description>
			<content:encoded><![CDATA[<p>We have a C++/C# based application where I work, and we currently use VBScript as a scripting language. Needless to say, we want to replace it, and we&#8217;ve decided that Javascript is a good candidate.</p>
<p>When it comes to executing Javascript in .NET, there are quite a few options. We have narrowed it down to <a href="http://jint.codeplex.com/" title="Jint">Jint</a> and <a href="http://jurassic.codeplex.com/" title="Jurassic">Jurassic</a>. They are quite similar, but they have some key differences which I will address here.</p>
<h2>Jint</h2>
<p>Jint is an interpreter based on <a href="http://www.antlr.org/" title="ANTLR">ANTLR</a> which means that the Javascript code is interpreted and executed each time a script is run.</p>
<h2>Jurassic</h2>
<p>Jurassic isn&#8217;t an interpreter like Jint, but has a compiler that compiles the Javascript into .NET byte-code. While that does offer a performance boost on subsequent runs of the same compiled code, we probably wouldn&#8217;t notice that since we&#8217;re going to compile and execute all scripts every time they run for simplicity&#8217;s sake.</p>
<h2>Pros and cons</h2>
<p>I&#8217;ve evaluated the two quite and lot, and I&#8217;ve dug through the code to look at how easy it would be to fix things I run across. Both projects are well structured, and it&#8217;s easy to find you&#8217;re way in the source code.</p>
<h3>Jint</h3>
<p class="ul_caption">Pros</p>
<ul>
<li>Easy to get started with, just one dll and it just works.</li>
<li>Extremely easy to expose .NET objects and functions to Javascript, and to return Javascript objects and functions.</li>
<li>The source code is nicely structured and easy to understand and modify.</li>
<li>When Javascript errors occur, you get a really nice error message with line numbers as you&#8217;d expect.</li>
<li>Exposes a debugging API, which means that we could implement our own debugging GUI for Javascript</li>
</ul>
<p class="ul_caption">Cons</p>
<ul>
<li>All of the ECMAScript5 functionality isn&#8217;t implemented, such as Array.prototype.every. This is a minor con, since it&#8217;s easy to either implement it in Javascript or add them to Jint.</li>
<li>Doesn&#8217;t respect &#8220;use strict&#8221;. Instead you specify strict mode as an option to the engine, which means that it&#8217;s either on or off for the whole script and you can&#8217;t trigger strict mode for a single block. Also a minor con since we would want all of our scripts to run in strict mode, regardless of &#8220;use strict&#8221;.</li>
<li>The implementation is not as rock solid as Jurassic. I&#8217;ve had to hunt down and fix some bugs myself (<a href="http://jint.codeplex.com/workitem/6950">#6950</a>, <a href="http://jint.codeplex.com/workitem/6949">#6949</a>, <a href="http://jint.codeplex.com/workitem/6948">#6948</a>). It does worry me that these bugs existed, but since it has been a pleasure to work with the well structured code in Jint, it&#8217;s been quite easy for me to fix them.</li>
<li>The project doesn&#8217;t seem to be as actively maintained as Jurassic.</li>
</ul>
<h3>Jurassic</h3>
<p class="ul_caption">Pros</p>
<ul>
<li>Seems like a more solid implementation, I didn&#8217;t find any bugs like I did with Jint.</li>
<li>Easy to get started with, just one dll and it just works.</li>
<li>The source code is nicely structured and easy to understand and modify.</li>
<li>The project seems to be quite actively maintained.</li>
<li>All of ECMAScript5 is implemented, and future Javascript features will likely come to Jurassic before they come to Jint.</li>
</ul>
<p class="ul_caption">Cons</p>
<ul>
<li>Isn&#8217;t nearly as easy to expose .NET objects as Jint. All objects you want to expose to Javascript needs to inherit from the Jurassic ObjectInstance class. I understand and appreciate the reason behind it since it means that all objects in Javascript can be treated the same way, regardless of whether it&#8217;s an exposed .NET object or a Jurassic object. But it means that we need a proxy class for each object we want to expose that transform the object into a Jurassic ObjectInstance. You could probably automate this by using reflection, so this is sort of a minor con.</li>
<li>When Javascript errors occur, you don&#8217;t get the offending line number. This is a real show stopper for us. VBScript (which we currently use as a scripting language) doesn&#8217;t give us this either, and it&#8217;s one of the biggest reasons for us to change language.</li>
<li>Offers debugging, but it seems like it&#8217;s only inside Visual Studio, which our script authors won&#8217;t have access to. And when debugging is enabled, the compiled assembly isn&#8217;t released from memory, which could become an issue for us.</li>
<li>This is more of an annoyance, but Jurassic doesn&#8217;t allow a return statement outside of a function, which means that your script can&#8217;t look like this:
<pre class="brush: jscript;">
var obj = {
  prop1: 1
}
return obj;
</pre>
<p>and then evaluate that script and get the returned Javascript object. Jurassics Evaluate method takes the last line in the script, evaluates it and returns it, which means that you&#8217;d have to do something like this:</p>
<pre>
var result = engine.Evaluate("var global_return = function() { " + scriptCode + " }; global_return();");
</pre>
</li>
</ul>
<h2>Conclusion</h2>
<p>We will probably use Jint as our Javascript engine. It&#8217;s a tight race, but there were some things that made us choose Jint.<br />
While Jurassic is a more solid Javascript implementation, the errors we&#8217;ve found in Jint are either edge cases or easy to fix. The things that tipped the scale in Jints favor are the detailed Javascript errors, and how easy it is to expose .NET objects to Jint.</p>
<p>If our needs were more geared towards having a lot of logic and functionality in Javascript, and not how easy it is to expose .NET functionality and having small pieces of Javascript to control the flow of the application, we would probably have chosen Jurassic instead.</p>
]]></content:encoded>
			<wfw:commentRss>http://coffeescripter.com/2012/05/embedding-javascript-in-net/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Working with mobile web applications</title>
		<link>http://coffeescripter.com/2012/01/working-with-mobile-web-applications/</link>
		<comments>http://coffeescripter.com/2012/01/working-with-mobile-web-applications/#comments</comments>
		<pubDate>Wed, 25 Jan 2012 09:38:21 +0000</pubDate>
		<dc:creator>Andy</dc:creator>
				<category><![CDATA[Mobile Web]]></category>

		<guid isPermaLink="false">http://coffeescripter.com/?p=270</guid>
		<description><![CDATA[So for the past year, I&#8217;ve been working almost exclusively on a mobile web application that is designed to run on Android and iPhone. It works quite well on Windows Phone (Mango) as well, but none of our customers have WP devices (yet). The application is a LOB app with offline capabilitites, so it&#8217;s mostly [...]]]></description>
			<content:encoded><![CDATA[<p>So for the past year, I&#8217;ve been working almost exclusively on a mobile web application that is designed to run on Android and iPhone. It works quite well on Windows Phone (Mango) as well, but none of our customers have WP devices (yet).</p>
<p>The application is a LOB app with offline capabilitites, so it&#8217;s mostly a standard CRUD app. While developing this application, I&#8217;ve learned a lot about the different quirks in the browsers on Android and iPhone, and this is what this blog post is going to be about.</p>
<h3>Application Cache</h3>
<p>Using the application cache is a must for anyone who wants to develop a web app with offline capabilities. At first we ignored the application cache, because we just couldn&#8217;t get it working. The problem was that as soon as the application cache was updated, it was impossible to send a request to the server. Turns out that we just didn&#8217;t read the spec, and we were missing:</p>
<pre>
NETWORK:
*
</pre>
<p>in the manifest.</p>
<h4>User specific cache</h4>
<p>To use the application cache, we needed to cache views depending on which user was logged in. So setting:</p>
<pre class="brush: xml;">
&lt;html manifest=&quot;/Manifest&quot;&gt;
</pre>
<p>on our start page was out of the question, since that would mean the browser would download the manifest even if you&#8217;re not logged in. Instead, we decided to use an iframe which loads once you have logged in. The contents of the iframe looks something like this:</p>
<pre class="brush: xml;">
&lt;!DOCTYPE html&gt;
&lt;html manifest=&quot;/Manifest&quot;&gt;
&lt;head&gt;
    &lt;script type=&quot;text/javascript&quot;&gt;
    var app_cache = window.parent.jQuery(applicationCache);

    app_cache.bind(&quot;cached checking downloading error noupdate obsolete progress updateready&quot;, function(event) {
        window.parent.ApplicationCacheEventDispatcher.trigger(event, applicationCache);
    });
    &lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>So when you log in, we use Javascript to append an iframe pointing to that html file. The Javascript in the iframe makes sure that any application cache event that is caught in the iframe gets passed on to the main window, which lets our application display a loading message to the user. </p>
<p>Just don&#8217;t forget to print out the user id or something unique for the logged in user in the manifest, otherwise the application cache won&#8217;t be updated if the user logs out, and logs in with a different account. Our solution to this is to print out the user id and application version as a comment in the manifest, like this:</p>
<pre class="brush: xml;">
CACHE MANIFEST

# version: @Version
# user: @User.Id

CACHE:
/
[...]
</pre>
<h4>Forcing an upgrade</h4>
<p>Sometimes you need to make breaking changes between versions, and you need to make sure that the application cache is updated on all devices before your users can continue to use the application.</p>
<p>An issue we ran into quite a lot at first was that after a customer had upgraded the application on the server, random errors occured for their users. This happened because the users still had the old Javascript files. That is, the application cache wasn&#8217;t updated fast enough. </p>
<p>To get around this, we started to pass the version number along with every request to the server. That gave us the option to check the version that came with the request, compare it to the server version, and tell the client to update the application cache if necessary.</p>
<h4>HTTP status == 0</h4>
<p>A couple of weeks ago, a bug report came in where a user was using the offline mode in the application. He went to another site, then came back to the application only to find it unusable. None of the pages would load from the application cache. Turns out that by browsing to another site and then returning and trying to fetch something from the application cache can result in getting a HTTP status of 0 instead of 200 in Android. And because of the incorrect HTTP status, jQuery reported it (correctly) as a failed request. So we needed to change the code to take this into account. A somewhat simplified version:</p>
<pre class="brush: jscript;">
function get(url, on_success, on_error) {
    $.get(url, {},
        function succ(response, textStatus, XHR) {
            on_success &amp;&amp; on_success(response, textStatus, XHR);
        },
        function err(jqXHR) {
            if (jqXHR.status === 0) {
                if (jqXHR.responseText.trim() == &quot;&quot;) {
                    on_error &amp;&amp; on_error(jqXHR);
                } else {
                    on_success &amp;&amp; on_success(jqXHR.responseText, &quot;ok&quot;, jqXHR);
                }
            } else {
                on_error &amp;&amp; on_error(jqXHR);
            }
        }
    );
}
</pre>
<h3>localStorage</h3>
<p>LocalStorage works mostly as you expect it; it&#8217;s a simple key-value-store with a finite amount of storage, and once you hit that you get an exception. But we got a really wierd bug report from a user where he would browse to another site, and come back to the application to find that all of his settings and data were gone.</p>
<p>Turns out that under some circumstances, Android doesn&#8217;t load the localStorage data when you hit the back button. I&#8217;m guessing it has something to do with the fact that Android doesn&#8217;t always reload the page when you go back, it loads it from the browser cache (not the application cache) instead.</p>
<p>So to get around this Android bug, we set a persistent value in localStorage which we use as a check to see if localStorage is correctly loaded.</p>
<pre class="brush: jscript;">
var check = &quot;1234567890&quot;
localStorage.setItem(&quot;android_check&quot;, check);
</pre>
<p>and when we want to fetch something from localStorage, we do:</p>
<pre class="brush: jscript;">
var hasItem = function() {
  return (typeof localStorage[key] != &quot;undefined&quot; &amp;&amp; localStorage[key] !== null);
}
var getItem = function(key, def) {
  if (!hasItem(key)) {
    if (localStorage.getItem(&quot;android_check&quot;) !== check) {
      // Reload the page so Android reloads localStorage
      window.location.reload();
    }
    return def;
  }
  return localStorage.getItem(key);
}
</pre>
<h3>overflow: scroll</h3>
<p>Our application sometimes needs to open a popup menu with different options, and that menu needs to be scrollable. This is simple in iOS5 since it supports overflow:scroll but in Android, not so much. And it&#8217;s not just that, there are differences in how you have to solve it for Android 2 and 3. This because you can&#8217;t set scrollTop on elements with overflow:hidden in Android 3, but it works for Android 2. </p>
<p>The way we solved it in Android 3 was to set overflow:visible and setting a fixed height on a wrapper element, and then adjusting the menus margin-top in a touchmove event handler. Needless to say, the scrolling experience in Android 3 is horrible compared to iOS5 and Android 2, but at least it works.</p>
<h3>Inputs in Android</h3>
<p>I don&#8217;t know how many hours I&#8217;ve spent fiddling with making inputs on Android play nicely. The root of the problem is that Android doesn&#8217;t use the browsers built-in input controls, but instead places some other wierd, internal input above the browsers input field.</p>
<h4>Setting focus on an input field</h4>
<p>The forms in our application works in a quite specific way. Instead of just displaying the input fields directly, we have a display element that is hidden and replaced with the real input when you tap on the wrapping element. </p>
<p>That is, the tap event handler for the wrapping element calls .hide() on the display element, and .show().focus() on the input. The reason we do this is to be able to format the display in a different way than when you edit the value.</p>
<p>The problem with this is that calling .focus() on an input in Android doesn&#8217;t bring up the keyboard, unless the call to .focus() happens in a click event handler. This is a minor issue for us, because the tap event handler gets called about half a second before a click event occurs, which gives us time to show the real input, and when the actual click occurs, the input is visible and catches the click, and the keyboard is displayed.</p>
<p>The real problem is if you want to give an input focus when you click somewhere else in the application. It simply doesn&#8217;t work, the user has to tap twice for that; once on our custom edit button to show the input, and then once on the input to get the keyboard.</p>
<h3>Page animations</h3>
<p>When you go from one page to another, the old page is transitioned out to the left, and the new page comes in from the right. While CSS transitions is very much possible in Android, it&#8217;s actually a much smoother experience to use jQuery.animate(), espcially if the pages are long. But I hear that Android 4 has hardware accelerated CSS transitions, so I hope to get a better result there.</p>
<p>An issue with page animations is the scroll position when you go from one page to another. When you hit the back button, you want to land on the same scroll position as when you left that page. This just works in Android, the scrolltop is automatically set correctly. But on iPhone, you&#8217;re back to the top of that page, which kinda sucks.<br />
The way we&#8217;ve solved this is to save the $(window).scrollTop() before a page animation starts, and then when the pages have finished animating, check if there is a saved scrolltop for the current url. If there is one, we set the $(window).scrollTop() to that, but only if $(window).scrollTop() == 0.</p>
]]></content:encoded>
			<wfw:commentRss>http://coffeescripter.com/2012/01/working-with-mobile-web-applications/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Extending built in objects in a safer way in Javascript</title>
		<link>http://coffeescripter.com/2011/05/extending-built-in-objects-in-a-safer-way-in-javascript/</link>
		<comments>http://coffeescripter.com/2011/05/extending-built-in-objects-in-a-safer-way-in-javascript/#comments</comments>
		<pubDate>Sun, 15 May 2011 10:55:21 +0000</pubDate>
		<dc:creator>Andy</dc:creator>
				<category><![CDATA[Javascript]]></category>

		<guid isPermaLink="false">http://coffeescripter.com/?p=238</guid>
		<description><![CDATA[In Javascript, its very easy to extend built in objects like Object, Array and String. You might find yourself wanting string methods that aren&#8217;t built into the String object, and it&#8217;s much nicer to read &#8220;one short sentence&#8221;.toUpperFirst(), than toUpperFirst(&#8220;one short sentence&#8221;). The problem is that by extending the builtin objects, you are adding global [...]]]></description>
			<content:encoded><![CDATA[<p>In Javascript, its very easy to extend built in objects like Object, Array and String. You might find yourself wanting string methods that aren&#8217;t built into the String object, and it&#8217;s much nicer to read &#8220;one short sentence&#8221;.toUpperFirst(), than toUpperFirst(&#8220;one short sentence&#8221;). The problem is that by extending the builtin objects, you are adding global symbols. Global symbols carry much of the same problems of global variables; you risk other parts of the system defining a global symbol with the same name. You might add the &#8220;toUpperFirst&#8221; function to the String object, and along comes another developer on your project who also needs to add toUpperFirst to the String object. Now, your implementation only changes the first char in the string and leaves the rest untouched, but the other developer decides that it&#8217;s a good idea to make the rest of the string lower case. Both yours and his code will work, most of the time, but because of the difference in your implementations, wierd bugs that just &#8220;shouldn&#8217;t happen&#8221; will occur.</p>
<p>In .NET, there is something called Extension Methods, which are basically the same as extending a builtin object in Javascript. It might look something like this:</p>
<pre class="brush: csharp;">
using System;

namespace MyAppExtensions
{
    static public class Extensions
    {
        public static string ToUpperFirst(this String s)
        {
            return s.Substring(0).ToUpper() + s.Substring(1);
        }
    }
}
</pre>
<pre class="brush: csharp;">
using System;
using MyAppExtensions;

namespace MyApp
{
    public class SomeClass
    {
        public SomeClass()
        {
            var myString = &quot;one short sentence&quot;.ToUpperFirst();
        }
    }
}
</pre>
<p>The key thing here is that you can hide your extension methods in a specific namespace, here called MyAppExtensions. So if anyone wants to use this extension, they need to add &#8220;using MyAppExtensions;&#8221; in their code. So it doesn&#8217;t pollute the global namespace, which is good. You also get a compile-time error if you use two namespaces which define the same extension method.</p>
<p>But you can achive basically the same thing in Javascript by using closures. Let&#8217;s say that you&#8217;re writing a game where you need to pick a random element from an array often, and you would really like to be able to do:</p>
<pre class="brush: jscript;">
 [1, 2, 3].random()
</pre>
<p>You could just add random to Array.prototype, but you know the risks of it, so you don&#8217;t. Instead, you can do something like this:</p>
<pre class="brush: jscript;">
var extendArrayWithRandom = function(fn) {
    if (typeof Array.prototype.random != &quot;undefined&quot;) {
        throw &quot;Cannot redefine Array.prototype.random&quot;;
    }
    var random = function() {
        var key = Math.round(Math.random() * (this.length - 1));
        return this[key];
    }
    Array.prototype.random = random;
    fn();
    if (Array.prototype.random !== random) {
        throw &quot;Array.prototype.random was redefined&quot;;
    }
    Array.prototype.random = undefined;
}
</pre>
<p>And use it like this:</p>
<pre class="brush: jscript;">
extendArrayWithRandom(function() {
    console.log([1, 2, 3, 4, 5].random()); // will output a number between 1 and 5
});
console.log([1, 2, 3, 4, 5].random()); // will throw an error because
                                       // random is no longer a method on
                                       // the array prototype
</pre>
<p>This way, [].random will only exist inside the function that you pass into extendArrayWithRandom(), and if anyone else has defined a global random function for Array, an error is thrown so we don&#8217;t risk any confusion. It also checks that noone has redefined Array.prototype.random during the execution of our function. This because it would possibly produce even more confusing results if someone defined global extension during run time without checking if one already exists.</p>
<h2>Callbacks</h2>
<p>As mentioned in the comments below, this gets a little tricky if you combine it with callbacks/asynchronous events. Take this for example:</p>
<pre class="brush: jscript;">
extendArrayWithRandom(function() {
    loadJson(&quot;/settings&quot;, function(settings) {
        var rand = settings.random();
    });
});
</pre>
<p>Now assuming that loadJson does an Ajax request, the function that we pass into loadJson will execute later than the one we pass into extendArrayWithRandom. This means that Array.prototype.random is no longer available in the Ajax callback, because as soon as the function we pass into extendArrayWithRandom is finished, we remove our implementation of Array.prototype.random.</p>
<p>To get around it, we need to be able to let extendArrayWithRandom return a new function. Something like this:</p>
<pre class="brush: jscript;">
var extendArrayWithRandom = function(fn) {
    var random = function() {
        var key = Math.round(Math.random() * (this.length - 1));
        return this[key];
    }

    return function() {
        if (typeof Array.prototype.random != &quot;undefined&quot;) {
            throw &quot;Cannot redefine Array.prototype.random&quot;;
        }
        Array.prototype.random = random;
        fn.apply(this, arguments);
        if (Array.prototype.random !== random) {
            throw &quot;Array.prototype.random was redefined&quot;;
        }
        Array.prototype.random = undefined;
    }
}
</pre>
<p>We can still use it like we used to, but we have to make sure that we execute the function that it now returns:</p>
<pre class="brush: jscript;">
extendArrayWithRandom(function() {
    console.log([1, 2, 3, 4, 5].random());
})();
</pre>
<p>Notice the extra () at the end, which means that we execute the function directly when it&#8217;s returned to us. Since we&#8217;re now returning a function instead, we can get back to our Ajax example:</p>
<pre class="brush: jscript;">
extendArrayWithRandom(function() {
    loadJson(&quot;/settings&quot;, extendArrayWithRandom(function(settings) {
        var rand = settings.random();
    }));
    console.log([1, 2, 3, 4, 5].random());
});
</pre>
<p>Since we have two functions that will execute separatly, we need to call extendArrayWithRandom twice to make sure that these two functions will have Array.prototype.random, and that we clear it right after they have executed.</p>
<h2>Conclusion</h2>
<p>Adding methods to global objects is something that you should be quite careful with, simply because it changes the global state of your application, and it&#8217;s hard to predict the implications of that.</p>
<p>This method isn&#8217;t foolproof, since you can be affecting others by using it. As soon as you call another function in another module inside your extendArrayWithRandom, Array.prototype.random will be accessible to them as well. Now that probably won&#8217;t cause trouble, but it&#8217;s hard to know for sure.</p>
]]></content:encoded>
			<wfw:commentRss>http://coffeescripter.com/2011/05/extending-built-in-objects-in-a-safer-way-in-javascript/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<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>15</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 [...]]]></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>3</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>9</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>2</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 [...]]]></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>1104</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. [...]]]></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>87</slash:comments>
		</item>
	</channel>
</rss>

