<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
	<channel>
		<title>Grauw’s web spot - Blog</title>
		<link>http://www.grauw.nl/</link>
		<description>This is the web log of Laurens Holst (aka Grauw). Topics here may range from MSX to web standards to stuff relating to my offline life :).</description>
		<language>en</language>
		<copyright>© 2004, Laurens Holst</copyright>
		<pubDate>Wed, 17 Feb 2010 03:08:19 +0100</pubDate>
		<docs>http://blogs.law.harvard.edu/tech/rss</docs>
		<atom:link href="http://www.grauw.nl/blog/rss.php" rel="self" type="application/rss+xml" />
		<image>
			<url>http://www.grauw.nl/images/sitelogo.png</url>
			<title>Grauw’s web spot</title>
			<link>http://www.grauw.nl/</link>
		</image>
				<item>
			<title>The view port element is… which?</title>
			<link>http://www.grauw.nl/blog/entry/549</link>
			<pubDate>Tue, 16 Feb 2010 22:16:36 +0100</pubDate>
			<description xml:base="http://www.grauw.nl/blog/entry/549"><![CDATA[<p>Browsers disagree quite vehemently on what constitutes the ‘view port element’, whether it is the <code>body</code> or the <code>html</code> element. Unfortunately you <em>do</em> need to know this from time to time, for example because the the <a href="http://www.w3.org/TR/DOM-Level-3-Events/#events-Events-MouseEvent-clientX"><code>clientX</code></a> and <a href="http://www.w3.org/TR/DOM-Level-3-Events/#events-Events-MouseEvent-clientY"><code>clientY</code></a> properties on the mouse event object specify coordinates relative to the view port scroll position.</p>

<p>I did some tests a while ago of what element the <a href="https://developer.mozilla.org/en/DOM/Element.scrollTop"><code>scrollTop</code></a> is set on, and because I can not find any clear overview of when the view port is what elsewhere, I guess I might as well publish the results here:</p>

<table>
	<caption>Test results</caption>
	<thead>
		<tr>
			<th>Browser</th>
			<th><code>scrollTop</code> is set on</th>
			<th><code>scrollTop</code> in quirks mode</th>
		</tr>
	</thead>
	<tbody>
		<tr>
			<td>Internet Explorer 6</td>
			<td><code>documentElement</code></td>
			<td><code>body</code></td>
		</tr>
		<tr>
			<td>Internet Explorer 8 (IE7 mode)</td>
			<td><code>documentElement</code></td>
			<td><code>body</code></td>
		</tr>
		<tr>
			<td>Internet Explorer 8</td>
			<td><code>documentElement</code></td>
			<td><code>body</code></td>
		</tr>
		<tr>
			<td>Firefox 3.0</td>
			<td><code>documentElement</code></td>
			<td><code>body</code></td>
		</tr>
		<tr>
			<td>Firefox 3.6</td>
			<td><code>documentElement</code></td>
			<td><code>body</code></td>
		</tr>
		<tr>
			<td>Safari 3</td>
			<td><code>body</code></td>
			<td><code>body</code></td>
		</tr>
		<tr>
			<td>Safari 4</td>
			<td><code>body</code></td>
			<td><code>body</code></td>
		</tr>
		<tr>
			<td>Chrome 3</td>
			<td><code>body</code></td>
			<td><code>body</code></td>
		</tr>
		<tr>
			<td>Chrome 4</td>
			<td><code>body</code></td>
			<td><code>body</code></td>
		</tr>
		<tr>
			<td>Opera 9.6</td>
			<td><code>documentElement</code></td>
			<td><code>body</code></td>
		</tr>
		<tr>
			<td>Opera 10</td>
			<td><code>documentElement</code></td>
			<td><code>body</code></td>
		</tr>
	</tbody>
</table>

<p><a href="/blog/2010-02-16/viewport-test.html">The testcase</a> (<a href="/blog/2010-02-16/viewport-test-quirks.html">quirks mode version</a>).</p>

<p>Hopefully the WebKit folks will fix this inconsistency sometime soon, because the way it is now makes it kind of hard to implement a reliable future-proof generic <code>getViewPort()</code> method.</p>

<p>Probably the most robust way to determine the X and Y coordinates of a mouse event within the page is to leverage the non-standard <a href="https://developer.mozilla.org/en/DOM/event.pageX"><code>pageX</code></a> and <a href="https://developer.mozilla.org/en/DOM/event.pageY"><code>pageY</code></a> properties that <a href="http://www.quirksmode.org/dom/w3c_cssom.html#t42">most browsers support</a>, and fall back to using <code>clientX</code> and <code>clientY</code> otherwise:</p>

<pre class="code">if ('pageX' in event &amp;&amp; 'pageY' in event) {
    return new Point(event.pageX, event.pageY);
} else {
    var oDocument = (event.target || event.srcElement).ownerDocument;
    var oViewport = oDocument.compatMode == 'BackCompat' ?
                        oDocument.body : oDocument.documentElement;
    return new Point(
        oViewport.scrollLeft + event.clientX,
        oViewport.scrollTop + event.clientY
    );
}
</pre>

<p>p.s. relating to my <a href="/blog/entry/542">previous post</a>, note that I do use feature detection here for <code>pageX</code> and <code>pageY</code>. Didn’t mean to say feature detection is useless, just that it is not always the right solution, unlike what is preached by some.</p>

<p>Here I make an assumption that <code>pageX</code>, when/if implemented in IE, will be implemented correctly. Actually, given that this is a non-standardised property, perhaps it is not the most safe assumption to make. But then again, the property seems so simple, what could possibly go wrong. Right? Right? <em>*Prepares to revisit this code snippet once IE9 is released…*</em> :)</p>]]></description>
			<!--comments>url</comments-->
			<guid>http://www.grauw.nl/blog/entry/549</guid>
		</item>
				<item>
			<title>What’s wrong with feature detection?</title>
			<link>http://www.grauw.nl/blog/entry/542</link>
			<pubDate>Mon, 08 Feb 2010 21:25:58 +0100</pubDate>
			<description xml:base="http://www.grauw.nl/blog/entry/542"><![CDATA[<p>So, <a href="http://www.getfirefox.com/">Firefox 3.6</a> is released, and FCKEditor breaks. <a href="http://www.ardisson.org/afkar/2010/02/07/and-the-winner-is%E2%80%A6-2/">Blame is assigned</a> to browser detection, feature detection is promoted as the be-all end-all solution.</p>

<p>Except that browsers tend to implement their new features in a broken way. D’oh.</p>

<p>The <code>node.children.tags()</code> method is a good example. Originally an <abbr title="Internet Explorer">IE</abbr>-ism/feature, which can be useful for a slight performance optimisation. Along comes Safari with support for <code>tags()</code> but returning nodes from the <a href="http://hg.grauw.nl/grauw-lib/rev/e6b71f1bafef">entire document</a> instead of just the child nodes.</p>

<p>Firefox then decides to implement the children collection as well, however without <code>tags()</code> method and thus incompletely, <a href="http://hg.grauw.nl/grauw-lib/rev/e8e519ee8795">again breaking</a> my feature detection. And finally Opera goes in for the kill by throwing <a href="http://hg.grauw.nl/grauw-lib/rev/b0cfc509b105">an exception</a> when <code>tags()</code> is used in a document parsed as <abbr title="Extensible HyperText Markup Language">XHTML</abbr> (<abbr title="if I recall correctly">iirc</abbr>).</p>

<p>So after having to fix this stupid optimisation in my <a href="http://www.grauw.nl/projects/pc/selectors/">Selectors implementation</a> three times, what did I end up doing? Right,</p>

<pre class="code">if (browser_ie)
   return node.children.tags(name);
</pre>

<p>Another example of feature detection gone awry we had at <a href="http://www.backbase.com/">Backbase</a> when <abbr title="Internet Explorer 8">IE8</abbr> introduced <abbr title="JavaScript Object Notation">JSON</abbr> support. <abbr>IE8</abbr> manages to serialise <abbr title="Extensible Markup Language">XML</abbr> <code>DOMString</code>s (e.g. retrieved from <code>getAttribute()</code>) to <code>null</code> instead of <code>""</code>. Had we used browser detection instead of feature detection, the issue would not have occurred.</p>

<p><strong>Feature detection is overrated.</strong> Because of this kind of crap I went back to (a sensible form of) browser detection, with the much more workable presumption that once implemented, browsers will not remove or break existing functionality. Yes, when the browser gets native support for whatever you want to use, it runs a little slower than possible initially. But in exchange you get the opportunity to explicitly test the feature before using it it.</p>

<p>Now I’m not saying feature detection is never good, there are cases where what you want to use is relatively simple, standardised and often-used on the web, like the <code>addEventListener()</code> method, and for such things feature detection is probably a safe bet. But be careful, and do realise that the history of browsers has shown that they very <em>very</em> much like to implement their new <abbr title="Application Programming Interfaces">APIs</abbr> and technologies in a broken way the first time around.</p>

<p>And there is of course the one golden rule: never depend on broken behaviour.</p>]]></description>
			<!--comments>url</comments-->
			<guid>http://www.grauw.nl/blog/entry/542</guid>
		</item>
				<item>
			<title>Object-oriented programming in JavaScript</title>
			<link>http://www.grauw.nl/blog/entry/540</link>
			<pubDate>Mon, 01 Feb 2010 11:49:29 +0100</pubDate>
			<description xml:base="http://www.grauw.nl/blog/entry/540"><![CDATA[<p>A long time ago I posted about object oriented programming and creating classes in JavaScript. That being a bit outdated, and me knowing a lot more about JavaScript now, I decided to make another post on that topic.</p>

<p>It is possible to produce <abbr title="Object Oriented Programming">OOP</abbr> class-like definitions using JavaScript functions and prototypes. What follows is a description of syntax, best practices and oddities of this. The syntax used here uses no external libraries.</p>

<p>This syntax is also picked up by <a href="http://www.eclipse.org/">Eclipse</a>’s <abbr title="JavaScript Development Toolkit">JSDT</abbr> plugin, which will provide you with a convenient object outline, code completion and more. JSDT is packaged with Eclipse <abbr title="Enterprise Edition">EE</abbr> by default.</p>

<h4>Creating classes</h4>

<p>JavaScript classes and methods are created in the following manner:</p>

<pre class="code">var MyClass = function() {
    // constructor
};

MyClass.prototype.myMethod = function() {
    // method
};

MyClass.myStaticMethod = function() {
    // static method
};
</pre>

<p>Convention for class names is to start with an upper-case letter (CamelCase), and members start with a lower-case letter (camelCase).</p>

<p>You instantiate an object using the <code>new</code> operator, e.g. <code>return new MyClass();</code>.</p>

<h4>Documenting classes</h4>

<p>Class and member documentation is created using <a href="http://code.google.com/p/jsdoc-toolkit/w/list">JSDoc annotations</a>, like so:</p>

<pre class="code">/**
 * Constructor description
 * @param bOption The first parameter
 * @class
 * Class description
 */
var MyClass = function(bOption) {
    // constructor
};

/**
 * Method description
 * @param {Array} oList The first parameter
 * @return {boolean} The result
 */
MyClass.prototype.doSomething = function(oList) {
    // method
};
</pre>

<p>It is recommended to create these always. The example’s method documentation also shows optional type annotations.</p>

<h4>Creating class properties</h4>

<p>Class properties should always be initialised in the constructor, so that you can use the constructor as a reference of which properties the object has, and so that the object is always in a defined state:</p>

<pre class="code">var MyClass = function() {
    this.myProperty = null;
};

MyClass.prototype.getMyProperty = function() {
    return this.myProperty;
};

MyClass.prototype.setMyProperty = function(oValue) {
    return this.myProperty = oValue;
};
</pre>

<p>Properties should generally be considered private, unless explicitly mentioned as public in the <code>@class</code> annotation. The reason for this is that JavaScript does not have property getters and setters (in all browsers), so Java’s methodology of creating <code>getSomething()</code> and <code>setSomething()</code> getter/setter methods is adopted. Accessor methods are essential to be able to deal with changing requirements, refactoring and performance optimisation in a straightforward manner and without compatibility problems.</p>

<p>Guideline for public properties: sometimes for convenience you want to make an exception. If you really must, direct references to other objects (<code>Action.record</code>) or primitive types (<code>Channel.id</code>, <code>Field.value</code>) are candidates for consideration. Avoid accessing arrays and hash maps directly though, so that you can easily change and optimise the implementation underneath. When in doubt you should use accessor methods.</p>

<p id="prototype-properties">Properties <em>can</em> also be defined directly on the prototype, however this is <em>not recommended</em>. Example:</p>

<pre class="code">var MyClass = function() {
};

MyClass.prototype.firstProperty  = null;               // okay (but beware!)
MyClass.prototype.secondProperty = 100;                // okay (but beware!)
MyClass.prototype.thirdProperty  = new OtherClass();   // bad
</pre>

<p>The reason why this is not recommended is because when a property is defined on the prototype, it will only be instantiated once. For null or primitive types (string, number, bool) this is not a problem. However for objects like in the third example, the OtherClass instance will not be unique for each new MyClass instance and be shared, risking unforeseen problems. Therefore, in order to not confuse those not aware of this detail, I consider this pattern as a whole bad practice.</p>

<p>Although not being recommended, the example provided above is given to provide better understanding of how JavaScript objects work, and for that occasional case where you really want to draw out that last bit of JavaScript performance.</p>

<h4>Extending classes</h4>

<p>To inherit from another class you need a small <code>extend()</code> utility function:</p>

<pre class="code">var MyClass = function() {
    MyBaseClass.call(this);    // call super
};

MyClass = extend(MyBaseClass, MyClass);

MyClass.prototype.doSomething = function(sArgument) {
    MyBaseClass.prototype.doSomething.call(this, sArgument);    // call super
};

/**
 * Class extension utility function
 * @param cBase The base class
 * @param fConstructor The constructor function for the new class
 */
function extend(cBase, fConstructor) {
    var cPrototype = new Function;
    cPrototype.prototype = cBase.prototype;
    fConstructor.prototype = new cPrototype;
    fConstructor.prototype.constructor = fConstructor;
    return fConstructor;
}
</pre>

<p>Here, <code>MyClass</code> inherits from <code>MyBaseClass</code>, and <code>MyClass</code>’s constructor invokes the parent object’s constructor. The <code>doSomething()</code> method shows how to call a base method.</p>

<p>You can check whether something is an instance of a certain class using the <code>instanceof</code> operator, e.g. <code>return new MyClass() instanceof MyBaseClass ? 'yes' : 'no';</code>.</p>

<h4>Namespacing</h4>

<p>Usually, an object will be ‘namespaced’ like so:</p>

<pre class="code">myNamespace = new function() {
    
    var MyClass = function() {
    };
    
    // export
    this.MyClass = MyClass;
    
};
</pre>

<p>Here a global <code>myNamespace</code> namespace object is created, and at the end the local <code>MyClass</code> class is exported as a member of the namespace object.</p>]]></description>
			<!--comments>url</comments-->
			<guid>http://www.grauw.nl/blog/entry/540</guid>
		</item>
				<item>
			<title>Saving time with Mercurial</title>
			<link>http://www.grauw.nl/blog/entry/538</link>
			<pubDate>Tue, 05 Jan 2010 23:47:17 +0100</pubDate>
			<description xml:base="http://www.grauw.nl/blog/entry/538"><![CDATA[<p>At work, we use <abbr title="Subversion">SVN</abbr>. As a <a href="http://mercurial.selenic.com/">Mercurial</a> convert, I’d like to share three examples that I encountered today where the Mercurial distributed revision control system could’ve saved me time and headaches.</p>

<h4>1. Reduced risk of breaking the trunk</h4>

<p>Today I left an hour later than I liked to, because I had checked in some changes which turned out to be broken. Since Wednesday is my day off, I could not fix the problem first thing the next morning, and leaving it the way it was would be a big inconvenience to my colleagues.</p>

<p>The underlying problem is that with <abbr>SVN</abbr>, every time you check in it ends up in the shared repository. Because the trunk needs to be kept in a working state, this requires a lot of testing effort for every check-in. In practice, this testing often doesn’t happen thoroughly enough, and sometimes a broken change slips through.</p>

<p>With Mercurial, you commit your changes to a local repository that is not shared, and every once in a while you synchronise your local repository with the shared (trunk) repository. This relieves you of a lot of testing effort, as you only need to test thoroughly before sharing your changes with the main repository, rather than for each individual check-in.</p>

<p>In this case after finding that there still were some issues, I could’ve simply gone home without synchronising my latest set of changes with the server.</p>

<h4>2. Narrowing down the source of problems</h4>

<p>Usually I make small incremental commits. By doing this I keep the amount of uncommitted changes low, so that I can easily compare my current code with the last working state in the version control system.</p>

<p>At a certain point though I was working on a big change, and I had to hold back on committing intermediate results because I knew it wasn’t fully functional yet, after all we can’t have the trunk in a broken state. Yet because of this, every time something did not work any more it was very hard to find what changes exactly caused it.</p>

<p>Since with Mercurial commits are not shared with the main repository until you tell it to, I could’ve continued to do small commits, and saved myself a lot of debugging headaches.</p>

<h4>3. Checking in the parts that are ready</h4>

<p>One thing I always miss terribly when working with <abbr>SVN</abbr> is the ability to commit partial changes. Now admittedly this is strictly speaking not a Mercurial feature. Nevertheless <a href="http://tortoisehg.bitbucket.org/">TortoiseHg</a>, the Windows and Linux shell extension for Mercurial, is the only tool I know of that has this feature.</p>

<p>Often you have some changes that you would like to commit, but you also have some other changes that are not ready yet. A pretty tedious process usually follows: you make copies of the changed files, revert the files, compare them with the copies and copy over the changes that you want to commit. Then you commit those changes and copy back the original files.</p>

<p>With TortoiseHg this is all much simpler. In the commit window you can activate and deactivate individual changes within files, and thus only select the changes that you want to commit. This would have been convenient when I took a break from refactoring to fix a bug that a colleague reported.</p>

<p>In summary, where Mercurial really outshines <abbr>SVN</abbr> is working on several things at once and making small, manageable commits. It also reduces testing and debugging overhead, and lessens the risk of broken changes ending up on the trunk.</p>

<p>Sounds compelling to me! :)</p>]]></description>
			<!--comments>url</comments-->
			<guid>http://www.grauw.nl/blog/entry/538</guid>
		</item>
				<item>
			<title>Var and function in JavaScript</title>
			<link>http://www.grauw.nl/blog/entry/537</link>
			<pubDate>Wed, 30 Dec 2009 21:21:35 +0100</pubDate>
			<description xml:base="http://www.grauw.nl/blog/entry/537"><![CDATA[<p>The way JavaScript interprets the <code>var</code> and <code>function</code> statements can be confusing. Intuitively, you would think the statements are processed in the order that they appear. However, for <code>var</code> and <code>function</code> this is not the case. I’ll try to give some clarification.</p>

<p>Let’s start with <code>function</code>. First we need to clarify the difference between a function declaration and a function expression. A function is called a function declaration when it appears like so:</p>

<pre>function aaa() {}</pre>

<p>A function is a function expression when it is used as part of an expression. Makes sense, no? :) Some examples:</p>

<pre>var bbb = function() {}</pre>

<pre>ccc = function ddd() {}</pre>

<p>Now before the JavaScript interpreter runs any code, it will start with gathering all function declarations. It creates local variables with their names, and assigns the compiled function objects to them. This means that function declarations can be called before they are declared, while function expressions can not.</p>

<p>Next, the interpreter will gather all <code>var</code> statements and create local variables for them. It will not initialize them yet though, the value will be <code>undefined</code> until the <code>var</code> statement is reached in normal execution of the code, which begins after this.</p>

<p>For example, the following code looks like it may have some issues. <code>ccc</code> is called before it’s defined, and you would think that if it is called <code>ccc</code> alerts “bbb is function”, not <code>undefined</code>. And if <code>var aaa</code> appears after the assignment, would <code>aaa</code> not be set on the global object instead of locally?</p>

<pre>function test() {
    
    ccc();
    
    aaa = true;
    
    var bbb = function() {
        alert('window.aaa is ' + window.aaa); // alerts “window.aaa is undefined”
    };
    
    function ccc() {
        alert('bbb is ' + bbb); // alerts “bbb is undefined”
    }
    
    var aaa;
    
    bbb();
    
}</pre>

<p>In reality this code is executed as if it were this:</p>

<pre>function test() {
    
    var ccc = function() {
        alert('bbb is ' + bbb); // alerts “bbb is undefined”
    };
    
    var bbb = undefined;
    var aaa = undefined;
    
    ccc();
    
    aaa = true;
    
    bbb = function() {
        alert('window.aaa is ' + window.aaa); // alerts “window.aaa is undefined”
    };
    
    bbb();
    
}</pre>

<p>So first <code>ccc</code> is defined as a local variable, then it is assigned the corresponding function object, then variables <code>bbb</code> and <code>aaa</code> are created and set to undefined, and after that the body continues to execute in code order, executing <code>ccc</code> (which is now available), assigning <code>aaa</code> and <code>bbb</code> their values and executing the latter.</p>

<p>Because of this you can do things in JavaScript which seem odd at first, but in practice are often very convenient, especially in combination with closures.</p>

<p>If you want to look up the details, see section 10.5 “Declaration Binding Instantiation” of the <a href="http://www.ecmascript.org/">ECMAScript 5 specification</a>.</p>
]]></description>
			<!--comments>url</comments-->
			<guid>http://www.grauw.nl/blog/entry/537</guid>
		</item>
		
	</channel>
</rss>