<?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>Erik A. Hanson &#187; Javascript</title>
	<atom:link href="http://www.eahanson.com/category/javascript/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.eahanson.com</link>
	<description>My weblog</description>
	<lastBuildDate>Mon, 24 May 2010 04:49:46 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Running Jasmine Tests Through Jaxer</title>
		<link>http://www.eahanson.com/2009/06/04/running-jasmine-tests-through-jaxer/</link>
		<comments>http://www.eahanson.com/2009/06/04/running-jasmine-tests-through-jaxer/#comments</comments>
		<pubDate>Fri, 05 Jun 2009 00:51:39 +0000</pubDate>
		<dc:creator>Erik</dc:creator>
				<category><![CDATA[Jasmine]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Jaxer]]></category>
		<category><![CDATA[Unit Testing]]></category>
		<category><![CDATA[Web development]]></category>

		<guid isPermaLink="false">http://www.eahanson.com/?p=98</guid>
		<description><![CDATA[Jasmine? Jaxer? Jasmine is a new Javascript testing framework from my pals at Pivotal Labs. Jaxer is an Apache module that wraps Firefox&#8217;s Javascript and rendering engine, providing a server-side Javascript environment that&#8217;s fast and compatible with any JS that works in Firefox (including all kinds of DOM manipulation and libraries like Prototype, jQuery, etc.). [...]]]></description>
			<content:encoded><![CDATA[<h3>Jasmine? Jaxer?</h3>
<p><a href="http://github.com/pivotal/jasmine/tree/master">Jasmine</a> is a new Javascript testing framework from my pals at <a href="http://pivotallabs.com/">Pivotal Labs</a>. </p>
<p><a href="http://www.aptana.com/jaxer">Jaxer</a> is an Apache module that wraps Firefox&#8217;s Javascript and rendering engine, providing a server-side Javascript environment that&#8217;s fast and compatible with any JS that works in Firefox (including all kinds of DOM manipulation and libraries like Prototype, jQuery, etc.).</p>
<h3>Running Jasmine Tests Through Jaxer</h3>
<p>Part of an app I&#8217;m writing uses Jaxer and I wanted to write my tests in Jasmine, so I wrote a test runner and reporter to bridge the two, and then I wrote a rake task to run the tests.</p>
<p>So now I can run &#8220;rake spec&#8221; and my JS tests will run, in Firefox, but without having to actually have Firefox open up (or be installed).</p>
<p>So:</p>
<pre>
rake spec
</pre>
<p>returns:</p>
<pre>
.    foo should do something.
.    foo should do something else.
.    foo should do yet another thing.

3 of 3 specs passed
</pre>
<p>And the whole thing takes <b>0.37 seconds</b>. It should be noted that those are trivial tests, but running a JS test suite with only 0.37 seconds of overhead is pretty neat.</p>
<p>My rake task looks like:</p>
<pre>
task :spec do
  results = `curl -s http://127.0.0.1:8081/jaxer-service/jasmine-jaxer`
  print results
  fail "spec failures" if results.match(/FAILURES!/)
end
</pre>
<h3>Download</h3>
<p>The JS code that hooks Jasmine to Jaxer is here: <a href="http://www.eahanson.com/code/jasmine-jaxer.js">jasmine-jaxer.js</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.eahanson.com/2009/06/04/running-jasmine-tests-through-jaxer/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>A Bookmarklet To Reload A Page&#8217;s CSS</title>
		<link>http://www.eahanson.com/2009/02/28/a-bookmarklet-to-reload-a-pages-css/</link>
		<comments>http://www.eahanson.com/2009/02/28/a-bookmarklet-to-reload-a-pages-css/#comments</comments>
		<pubDate>Sun, 01 Mar 2009 02:46:05 +0000</pubDate>
		<dc:creator>Erik</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Web development]]></category>

		<guid isPermaLink="false">http://www.eahanson.com/?p=62</guid>
		<description><![CDATA[Sometimes when I&#8217;m developing, I want to change some stylesheets and reload them without reloading the whole page. Often, I use Firebug or the Safari Web Inspector to play with individual attributes, but sometimes I have to edit the CSS files. So I wrote a bookmarklet to reload the files. Here it is: reload CSS [...]]]></description>
			<content:encoded><![CDATA[<p>Sometimes when I&#8217;m developing, I want to change some stylesheets and reload them without reloading the whole page. Often, I use Firebug or the Safari Web Inspector to play with individual attributes, but sometimes I have to edit the CSS files.</p>
<p>So I wrote a bookmarklet to reload the files. Here it is:</p>
<p><a href="javascript:(function()%20%7Bvar%20links%20=%20document.getElementsByTagName(%22link%22);for%20(var%20i%20=%200;%20i%20%3C%20links.length;%20i++)%20%7Bif%20(links%5Bi%5D.rel%20===%20%22stylesheet%22)%20%7Bif%20(links%5Bi%5D.href.indexOf(%22?%22)%20===%20-1)%20%7Blinks%5Bi%5D.href%20+=%20%22?%22;%7Dlinks%5Bi%5D.href%20+=%20%22x%22;%7D%7D%7D)()">reload CSS</a></p>
<p>(Just drag that into your bookmarks bar. Tested in Safari and Firefox.)</p>
<p>It works by appending the letter &#8220;x&#8221; after a &#8220;?&#8221; at the end of each stylesheet reference. That causes the browser to reload the stylesheet. Here&#8217;s the code:</p>
<pre>
var links = document.getElementsByTagName("link");
for (var i = 0; i < links.length; i++) {
  if (links[i].rel === "stylesheet") {
    if (links[i].href.indexOf("?") === -1) {
      links[i].href += "?";
    }
    links[i].href += "x";
  }
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.eahanson.com/2009/02/28/a-bookmarklet-to-reload-a-pages-css/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Introducing JS Dev Tools</title>
		<link>http://www.eahanson.com/2009/02/28/introducing-js-dev-tools/</link>
		<comments>http://www.eahanson.com/2009/02/28/introducing-js-dev-tools/#comments</comments>
		<pubDate>Sun, 01 Mar 2009 02:05:35 +0000</pubDate>
		<dc:creator>Erik</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[My Software]]></category>
		<category><![CDATA[Web development]]></category>
		<category><![CDATA[jsdevtools.com]]></category>

		<guid isPermaLink="false">http://www.eahanson.com/?p=57</guid>
		<description><![CDATA[I created a site called JS Dev Tools (jsdevtools.com) to keep track of useful Javascript development tools and libraries. Check out the site, subscribe to the feed, and suggest your favorite tools and libraries.]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.jsdevtools.com"><img src="http://www.eahanson.com/weblog/wp-content/uploads/2009/02/jsdevtools.png" alt="jsdevtools" title="jsdevtools" width="400" height="193" class="aligncenter size-full wp-image-59" /></a></p>
<p>I created a site called JS Dev Tools (<a href="http://www.jsdevtools.com">jsdevtools.com</a>) to keep track of useful Javascript development tools and libraries.</p>
<p>Check out <a href="http://www.jsdevtools.com">the site</a>, subscribe to <a href="http://www.jsdevtools.com/rss.xml">the feed</a>, and <a href="mailto:submissions@jsdevtools.com">suggest your favorite tools and libraries</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.eahanson.com/2009/02/28/introducing-js-dev-tools/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Relative dates in Javascript</title>
		<link>http://www.eahanson.com/2008/12/04/relative-dates-in-javascript/</link>
		<comments>http://www.eahanson.com/2008/12/04/relative-dates-in-javascript/#comments</comments>
		<pubDate>Thu, 04 Dec 2008 22:10:09 +0000</pubDate>
		<dc:creator>Erik</dc:creator>
				<category><![CDATA[Javascript]]></category>

		<guid isPermaLink="false">http://www.eahanson.com/?p=37</guid>
		<description><![CDATA[A while ago, I posted some Javascript code that produces a nice relative date string (e.g., &#8220;4 days ago&#8221; or &#8220;18 minutes ago&#8221;) given two dates. I looked at the code again and noticed that it was pretty long and needlessly required Prototype. So I cleaned it up a bit: /** * Simple relative date. [...]]]></description>
			<content:encoded><![CDATA[<p>A while ago, I <a href="http://www.eahanson.com/2007/10/31/my-time-zone-solution-relativedatejs-and-servertimejs/">posted some Javascript code</a> that produces a nice relative date string (e.g., &#8220;4 days ago&#8221; or &#8220;18 minutes ago&#8221;) given two dates.</p>
<p>I looked at the code again and noticed that it was pretty long and needlessly required <a href="http://prototypejs.org/">Prototype</a>. So I cleaned it up a bit:</p>
<pre>
/**
 * Simple relative date.
 *
 * Returns a string like "4 days ago". Prefers to return values >= 2. For example, it would
 * return "26 hours ago" instead of "1 day ago", but would return "2 days ago" instead of
 * "49 hours ago".
 *
 * Copyright (c) 2008 Erik Hanson http://www.eahanson.com/
 * Licensed under the MIT License http://www.opensource.org/licenses/mit-license.php
 */
function relativeDate(olderDate, newerDate) {
  if (typeof olderDate == "string") olderDate = new Date(olderDate);
  if (typeof newerDate == "string") newerDate = new Date(newerDate);

  var milliseconds = newerDate - olderDate;

  var conversions = [
    ["years", 31518720000],
    ["months", 2626560000 /* assumes there are 30.4 days in a month */],
    ["days", 86400000],
    ["hours", 3600000],
    ["minutes", 60000],
    ["seconds", 1000]
  ];

  for (var i = 0; i < conversions.length; i++) {
    var result = Math.floor(milliseconds / conversions[i][1]);
    if (result >= 2) {
      return result + " " + conversions[i][0] + " ago";
    }
  }

  return "1 second ago";
}
</pre>
<p>Try it out: <!-- use prototype just for this demo code -- it's not needed for relativeDate.js --><script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/prototype/1.6.0.3/prototype.js"></script><script type="text/javascript" src="/code/RelativeDate2/relativeDate.js"></script><script type="text/javascript">function demo() { $('resultArea').update(relativeDate($('older').value, $('newer').value)) }</script></p>
<div style="background-color: #ddd; padding: 1em; margin: 1em">
  Older date:<br />
<input type="text" style="width: 50em" id="older">
  <br/><br />
  Newer date:<br />
<input type="text" style="width: 50em" id="newer">
  <script type="text/javascript">
    $('older').value = new Date(new Date() - 1000000).toString();
    $('newer').value = new Date().toString();
  </script></p>
<p/>
  Relative date: <a name="result"><span id="resultArea">&nbsp;</span></a> (<a href="#result" onclick="demo()">Update</a>)
</div>
<p><script type="text/javascript">demo();</script></p>
<p>Raw code and tests:<br />
<a href="/code/RelativeDate2/relativeDate.js">relativeDate.js</a><br />
<a href="/code/RelativeDate2/relativeDateTest.html.txt">relativeDateTest.html</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.eahanson.com/2008/12/04/relative-dates-in-javascript/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>New Test Runner for JsUnit</title>
		<link>http://www.eahanson.com/2008/05/18/new-test-runner-for-jsunit/</link>
		<comments>http://www.eahanson.com/2008/05/18/new-test-runner-for-jsunit/#comments</comments>
		<pubDate>Mon, 19 May 2008 02:01:45 +0000</pubDate>
		<dc:creator>Erik</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[JsUnit]]></category>

		<guid isPermaLink="false">http://www.eahanson.com/2008/05/18/new-test-runner-for-jsunit/</guid>
		<description><![CDATA[Christian Williams created a new test runner for JsUnit. More info here.]]></description>
			<content:encoded><![CDATA[<p>Christian Williams created a new test runner for JsUnit. <a href="http://pivots.pivotallabs.com/users/kelly/blog/articles/450-standup-5-7-2008">More info here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.eahanson.com/2008/05/18/new-test-runner-for-jsunit/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A Rake Task to Concatenate and Compress Javascript Files</title>
		<link>http://www.eahanson.com/2008/03/02/a-rake-task-to-concatenate-and-compress-javascript-files/</link>
		<comments>http://www.eahanson.com/2008/03/02/a-rake-task-to-concatenate-and-compress-javascript-files/#comments</comments>
		<pubDate>Mon, 03 Mar 2008 06:15:52 +0000</pubDate>
		<dc:creator>Erik</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Ruby on Rails]]></category>
		<category><![CDATA[Web development]]></category>
		<category><![CDATA[wshlst.com]]></category>

		<guid isPermaLink="false">http://www.eahanson.com/2008/03/02/a-rake-task-to-concatenate-and-compress-javascript-files/</guid>
		<description><![CDATA[A while ago, I wrote about a Ruby script to concatenate and compress Javascript files for my wshlst application. I&#8217;ve changed things around a bit since that article, so I thought it was time for an update. Background wshlst uses a lot of Javascript. When developing, I want to have all of my JS files [...]]]></description>
			<content:encoded><![CDATA[<p>A while ago, I wrote about <a href="http://www.eahanson.com/2007/10/16/a-ruby-script-to-concatenate-and-compress-javascript-files/">a Ruby script to concatenate and compress Javascript files</a> for my <a href="http://www.eahanson.com/category/wshlstcom/">wshlst</a> application. I&#8217;ve changed things around a bit since that article, so I thought it was time for an update.</p>
<h3>Background</h3>
<p><a href="http://www.eahanson.com/category/wshlstcom/">wshlst</a> uses <a href="http://www.eahanson.com/2007/10/25/wshlstcom-a-webapp-with-a-pure-javascript-ui/">a lot of Javascript</a>. When developing, I want to have all of my JS files listed in my <code>index.html</code> page. But in production mode, I want a single JS file. So I wrote a script to read in my <code>index.html</code> file, find all the references to my Javascript files, and write out a new HTML file that contains a reference to a single JS file that was created by concatenating and compressing all the JS files.</p>
<p>As an example, have a look at what my <code>index.html</code> page looks like in <a href="http://eahanson.com/code/wshlst-index.txt">development mode</a> and in <a href="http://eahanson.com/code/wshlst-index-mini.txt">production mode</a>.</p>
<h3>Ruby Script &rarr; Rake</h3>
<p>When a server move prompted me to upgrade to Subversion and Capistrano, I decided to turn my Ruby script into a Rake task that I could trigger from my Capistrano deploy: <a href="http://www.eahanson.com/code/minify.rake">minify.rake</a></p>
<h3>Capistrano</h3>
<p>I added a line to my Capistrano <code>deploy.rb</code> file to run <code>rake minify</code> on the server after updating from Subversion:</p>
<pre>run "cd #{release_path} &#038;&#038; rake minify RAILS_ENV=#{rails_env}"</pre>
<h3>Apache</h3>
<p>I also added a few lines to my <code>httpd.conf</code> file to support this. First, since the Rake task combines all the JS files into a single JS file but Capistrano deploys the entire app, I wanted to restrict access to everything in the <code>javascripts</code> directory:</p>
<pre># Don't allow access to the javascripts directory (all JS should be in minified js file)
RewriteRule ^/javascripts/ - [F]</pre>
<p>Then, because the Rake task reads <code>index.html</code> and outputs a file called <code>index-mini.html</code>, I wanted to send all requests for <code>/</code> and <code>/index.html</code> to <code>/index-mini.html</code>:</p>
<pre>
# Rewrite index.html to index-mini.html
RewriteRule ^/index.html$ /index-mini.html [QSA]

# Rewrite index to check for static
RewriteRule ^/$ /index-mini.html [QSA]
</pre>
<h3>Why Not Use AssetPackager?</h3>
<p>For a normal Rails application, <a href="http://synthesis.sbecker.net/pages/asset_packager">AssetPackager</a> is probably the right solution to this problem. However, <a href="http://www.eahanson.com/category/wshlstcom/">wshlst</a> doesn&#8217;t use Rails to generate the UI (<a href="http://www.eahanson.com/2007/10/25/wshlstcom-a-webapp-with-a-pure-javascript-ui/">it&#8217;s all done in Javascript</a>), so AssetPackager wouldn&#8217;t work.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.eahanson.com/2008/03/02/a-rake-task-to-concatenate-and-compress-javascript-files/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Firing mouse events in tests</title>
		<link>http://www.eahanson.com/2008/01/01/firing-mouse-events-in-tests/</link>
		<comments>http://www.eahanson.com/2008/01/01/firing-mouse-events-in-tests/#comments</comments>
		<pubDate>Wed, 02 Jan 2008 04:17:48 +0000</pubDate>
		<dc:creator>Erik</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[JsUnit]]></category>
		<category><![CDATA[Unit Testing]]></category>
		<category><![CDATA[Web development]]></category>

		<guid isPermaLink="false">http://www.eahanson.com/2008/01/01/firing-mouse-events-in-tests/</guid>
		<description><![CDATA[The Bad News Sending mouse events such as click and mouseover in JsUnit tests can be really hard. More Bad News Prototype doesn&#8217;t make it any easier. Sam Stephenson says: We would very much like to support it in the future. It&#8217;s fairly complicated to implement native event firing across all supported browsers, so in [...]]]></description>
			<content:encoded><![CDATA[<h4>The Bad News</h4>
<p>Sending mouse events such as <code>click</code> and <code>mouseover</code> in <a href="http://jsunit.net">JsUnit</a> tests can be really hard.</p>
<h4>More Bad News</h4>
<p><a href="http://prototypejs.org">Prototype</a> doesn&#8217;t make it any easier. Sam Stephenson <a href="http://groups.google.com/group/prototype-core/browse_thread/thread/9fec287978138250">says</a>:</p>
<blockquote><p>
We would very much like to support it in the future.  It&#8217;s fairly complicated to implement native event firing across all supported browsers, so in 1.6.0, fire works with custom events only.
</p></blockquote>
<h4>YUI To The Rescue</h4>
<p><a href="http://developer.yahoo.com/yui/yuitest/#useractions">YAHOO.util.UserActions</a> can simulate some user actions. Unfortunately, calls to YUI can look a bit clunky in a Prototype-heavy codebase:</p>
<pre>
var element = new Element("div").insert("Hi");
var offset = element.cumulativeOffset();
YAHOO.util.UserAction.click(element, { shiftKey: true });
</pre>
<h4>YUI + Prototype FTW</h4>
<p>A little mixin magic:</p>
<pre>
Element.addMethods({
  simulateClick: YAHOO.util.UserAction.click.bind(YAHOO.util.UserAction),
  simulateDblClick: YAHOO.util.UserAction.dblclick.bind(YAHOO.util.UserAction),
  simulateMousedown: YAHOO.util.UserAction.mousedown.bind(YAHOO.util.UserAction),
  simulateMouseup: YAHOO.util.UserAction.mouseup.bind(YAHOO.util.UserAction),
  simulateMouseover: YAHOO.util.UserAction.mouseover.bind(YAHOO.util.UserAction),
  simulateMouseout: YAHOO.util.UserAction.mouseout.bind(YAHOO.util.UserAction),
  simulateMousemove: YAHOO.util.UserAction.mousemove.bind(YAHOO.util.UserAction)
});
</pre>
<p>and now our test code looks nicer:</p>
<pre>
var element = new Element("div").insert("Hi");
var offset = element.cumulativeOffset();
myElement.simulateClick({ shiftKey: true });
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.eahanson.com/2008/01/01/firing-mouse-events-in-tests/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>My time zone solution: RelativeDate.js and ServerTime.js</title>
		<link>http://www.eahanson.com/2007/10/31/my-time-zone-solution-relativedatejs-and-servertimejs/</link>
		<comments>http://www.eahanson.com/2007/10/31/my-time-zone-solution-relativedatejs-and-servertimejs/#comments</comments>
		<pubDate>Wed, 31 Oct 2007 21:29:05 +0000</pubDate>
		<dc:creator>Erik</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[My Software]]></category>
		<category><![CDATA[Ruby on Rails]]></category>
		<category><![CDATA[Web development]]></category>
		<category><![CDATA[wshlst.com]]></category>

		<guid isPermaLink="false">http://www.eahanson.com/2007/10/31/my-time-zone-solution-relativedatejs-and-servertimejs/</guid>
		<description><![CDATA[For my wshlst.com project, I needed to show when each item or comment was created or edited. My initial implementation was to just show the time and date of the change, but people who aren&#8217;t in the same time zone as my server didn&#8217;t like the fact that it showed a different time zone. I [...]]]></description>
			<content:encoded><![CDATA[<p>For my <a href="http://www.eahanson.com/category/wshlstcom/">wshlst.com</a> project, I needed to show when each item or comment was created or edited. My initial implementation was to just show the time and date of the change, but people who aren&#8217;t in the same time zone as my server didn&#8217;t like the fact that it showed a different time zone.</p>
<p>I contemplated having a per-user time zone setting, but that seemed complicated. So I decided to just show how old the item is. For that, I needed to write two things. I&#8217;m posting them here in case anyone else finds them useful.</p>
<h3>RelativeDate.js</h3>
<p>First, I needed a simple relative date formatter, so I wrote a simple one. Given two dates, it returns a string like </p>
<pre>
4 days ago
</pre>
<p>or </p>
<pre>
26 hours ago
</pre>
<p>Here&#8217;s the code and the <a href="http://jsunit.net">JsUnit</a> test:</p>
<p><a href="/code/RelativeDate/RelativeDate.js">RelativeDate.js</a><br />
<a href="/code/RelativeDate/RelativeDateTest.html.txt">RelativeDateTest.html</a></p>
<h3>ServerTime.js</h3>
<p>The timestamps of the items I&#8217;m displaying are stored in the database, so they are based on the clock of my database server. The relative dates are calculated in Javascript, so they are based on the clock of the user, which might be hours or just minutes off from the database server time. </p>
<p>The first thing my app does when it loads is checks to see if the user is logged in, so I decided to piggyback the current server time along with the response. Since the client and server talk using JSON, it&#8217;s simple to add another property to the response:</p>
<pre>
def current
  ...
  render_json({
    :success => true,
    :user => user,
    :servertime => dbtime()
  }.to_json)
end

...

def dbtime
  ActiveRecord::Base
    .connection
    .select_all("select unix_timestamp(now()) as now")[0]["now"]
    .to_i
end
</pre>
<p>I wrote a ServerTime class on the client side and I initialize it when the app receives the current user response from the server:</p>
<pre>
this.serverTime = new ServerTime(json.servertime);
</pre>
<p>Here&#8217;s the code (it&#8217;s very simple):</p>
<p><a href="/code/ServerTime.js">ServerTime.js</a></p>
<h3>Putting It Together&#8230;</h3>
<p>And now to display the relative time, my app only has to do this:</p>
<pre>
var updated = new Date(item.updated_at * 1000);
element.insert(new RelativeDate(updated, app.serverTime.get()).toString());
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.eahanson.com/2007/10/31/my-time-zone-solution-relativedatejs-and-servertimejs/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>wshlst.com: A Webapp With A Pure-Javascript UI</title>
		<link>http://www.eahanson.com/2007/10/25/wshlstcom-a-webapp-with-a-pure-javascript-ui/</link>
		<comments>http://www.eahanson.com/2007/10/25/wshlstcom-a-webapp-with-a-pure-javascript-ui/#comments</comments>
		<pubDate>Thu, 25 Oct 2007 22:51:08 +0000</pubDate>
		<dc:creator>Erik</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[My Software]]></category>
		<category><![CDATA[Web development]]></category>
		<category><![CDATA[wshlst.com]]></category>

		<guid isPermaLink="false">http://www.eahanson.com/2007/10/25/wshlstcom-a-webapp-with-a-pure-javascript-ui/</guid>
		<description><![CDATA[I created a little wish list website called wshlst.com for my family to use. (Read more about it here.) I worked on it a little bit before Christmas last year, and a little bit again this year. It&#8217;s been a lot of fun to write, and one reason is that the entire UI is written [...]]]></description>
			<content:encoded><![CDATA[<p>I created a little wish list website called <a href="http://www.wshlst.com/">wshlst.com</a> for my family to use. (<a href="http://www.eahanson.com/2007/10/24/wshlstcom/">Read more about it here</a>.) I worked on it a little bit before Christmas last year, and a little bit again this year.</p>
<p>It&#8217;s been a lot of fun to write, and one reason is that the entire UI is written in Javascript. No HTML, no CSS. There&#8217;s no HTML generation on the server-side either; it&#8217;s all client-side Javascript. I&#8217;d really like to write more apps like this.</p>
<h3>The Server</h3>
<p>There is of course a server-side component. I decided to write the server in Rails because I had just finished working on a Rails project at <a href="http://www.pivotallabs.com/">Pivotal Labs</a> and had Rails on the brain. Plus, my web host, <a href="http://www.dreamhost.com/r.cgi?29771">DreamHost</a>, supports Rails and doesn&#8217;t support Java, which is the language I&#8217;ve written all my other web apps in.</p>
<p>DreamHost&#8217;s support of Rails is a bit limited though: they kill any long-running processes, which means that a response from your Rails app could take 10 seconds if no other requests have been made lately. It&#8217;s good enough for a little project like Wshlst with only a few users and for initial development, but not much beyond that. (If I were to do it over again, I&#8217;d probably just use Ruby CGI, or maybe even PHP. Or use a VPS from <a href="http://www.rimuhosting.com/">Rimu</a>, but that costs money.)</p>
<p>Because all of the UI is in Javascript, the Rails side of things doesn&#8217;t have to generate any HTML. Instead, it takes standard Rails requests and returns <a href="http://json.org/">JSON</a> using <a href="http://json.rubyforge.org/">JSON for Ruby</a>. For example, the client sends the following AJAX request:</p>
<pre>
GET http://wshlst.com/user/list
</pre>
<p>and the server uses ActiveRecord magic to find all the users that are &#8220;friends&#8221; with the current user and uses JSON for Ruby to convert that list to JSON, which it returns back to the client like this:</p>
<pre>
[{name: "Andy Acorn", id: 12, email: "andy@example.com"},
{name: "Betty Beets", id: 13, email: "betty@example.com"},
{name: "Chad Carrot", id: 14, email: "chad@example.com"},
{name: "Donna Donut", id: 15, email: "donna@example.com"}]
</pre>
<p>which Prototype automatically converts to Javascript objects.</p>
<p>The server is of course also responsible for sending static files, but those are all handled by DreamHost&#8217;s Apache servers.</p>
<h3>The Client</h3>
<p>Here&#8217;s where it gets interesting. The app consists of an HTML file that does little more than include the Javascript files. (In development mode, there are multiple Javascript files, but when I deploy to production, there&#8217;s just one file. <a href="http://www.eahanson.com/2007/10/16/a-ruby-script-to-concatenate-and-compress-javascript-files/">Read this blog post on concatenating and compressing Javascript files with Ruby</a>.)</p>
<p>The app relies heavily on <a href="http://prototypejs.org/">Prototype</a>, and also uses <a href="http://www.berniecode.com/writing/animator.html">Animator.js</a> for a few visual effects. Everything else I wrote from scratch. I like to write a lot of code from scratch when I&#8217;m working on a personal project so I can get a good understanding of what&#8217;s really going on and be able to better evaluate pre-written libraries when I&#8217;m programming for money.</p>
<p>The app&#8217;s main class is called Application and acts as a controller. There are many view classes which are combined to form the app&#8217;s UI. For example, the &#8220;Change Password&#8221; box is implemented by a ChangePasswordForm class and consists of a ModalBox with a FormPanel inside. The FormPanel contains instances of Buttons and Fields. Writing a Field class of course takes more time than putting <tt>&lt;input type="text"&gt;</tt> in some template file somewhere, but it allows for easy reuse and the ability to add a feature to all fields in just one place. (I hope to post some of the code from Wshlst on this blog in the future.)</p>
<p>Responding to user actions is just a matter of one Javascript method directly calling another method. No parsing of parameters, no layers of actions and filters, no guessing client state on the server side. It&#8217;s very liberating. </p>
<h3>Lessons Learned</h3>
<p><b>Test early and often in lots of browsers.</b> This is obviously important when doing any web development, but when it&#8217;s 100% Javascript, there&#8217;s even more chance of incompatibilities. My <a href="http://jsunit.net/">JsUnit</a> tests caught some issues (<tt>Date.now</tt> turns out to be Firefox-only), but most issues I had were visual.</p>
<p><b>MVC is good.</b> Again, I already knew this, but I didn&#8217;t do nearly a good enough job with it in this app, probably because it was the first time I wrote an entire UI in Javascript. Next time, I&#8217;ll have multiple controllers and keep app logic out of the views as much as possible.</p>
<p><b>Events are probably the way to go.</b> Wshlst suffers from some tight coupling of objects because they directly notify each other of actions. Next time, I&#8217;ll try having all my objects send custom events to and receive custom events from some global event source (perhaps <tt>document.body</tt>), like I did back in the days when I wrote Mac software.</p>
<p><b>UI is hard.</b> I&#8217;m glad I did all the UI myself, but next time I&#8217;d like to build on the work of others. I&#8217;m still looking for a good Javascript widget library. Some of the widget libraries I&#8217;ve seen are trying to make web apps look application-y, and I&#8217;d prefer my web app to look web-y. Also, some libraries don&#8217;t have great support for calling everything from Javascript. I think I&#8217;ll look into <a href="http://dojotoolkit.org/">Dojo</a> again now that version 1.0 has been released, and more importantly, now that there&#8217;s more documentation.</p>
<h3>Try It Out</h3>
<p>There&#8217;s no way yet to sign up for Wshlst (if there&#8217;s enough interest I&#8217;ll do it), but the front page of the site lists some demo users you can use to play around: <a href="http://www.wshlst.com/">www.wshlst.com</a>.</p>
<p><i><a href="http://www.eahanson.com/category/wshlstcom/">Read more articles about wshlst.com</a></i></p>
]]></content:encoded>
			<wfw:commentRss>http://www.eahanson.com/2007/10/25/wshlstcom-a-webapp-with-a-pure-javascript-ui/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>A Ruby Script to Concatenate and Compress Javascript Files</title>
		<link>http://www.eahanson.com/2007/10/16/a-ruby-script-to-concatenate-and-compress-javascript-files/</link>
		<comments>http://www.eahanson.com/2007/10/16/a-ruby-script-to-concatenate-and-compress-javascript-files/#comments</comments>
		<pubDate>Wed, 17 Oct 2007 06:07:38 +0000</pubDate>
		<dc:creator>Erik</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Web development]]></category>

		<guid isPermaLink="false">http://www.eahanson.com/2007/10/16/a-ruby-script-to-concatenate-and-compress-javascript-files/</guid>
		<description><![CDATA[I&#8217;ve got an HTML page that includes a bunch of Javascript files, which makes development easy but which hurts performance in production. The standard solution is to concatenate all the Javascript files into one big file and then compress it. I wanted it to be automated of course, and I wanted to do it at [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve got an HTML page that includes a bunch of Javascript files, which makes development easy but which <a href="http://yuiblog.com/blog/2006/11/28/performance-research-part-1/">hurts performance</a> in production.</p>
<p>The standard solution is to concatenate all the Javascript files into one big file and then compress it. I wanted it to be automated of course, and I wanted to do it at deploy-time, not at run-time. </p>
<p>So I wrote a little script that figures out what Javascript files are being included in the HTML page, compresses them with the <a href="http://developer.yahoo.com/yui/compressor/">YUI Compressor</a>, concatenates them into a file named after the newly-compressed and -concatenated Javascript&#8217;s MD5 hash, and creates a copy of the original HTML page that references the new Javascript file instead of the old ones.</p>
<p>It&#8217;s pretty specific to my app&#8217;s needs, but with some minor tweaking, it should be useable on other projects. Check it out: <b><a href="http://www.eahanson.com/code/minify.rb">minify.rb</a></b></p>
]]></content:encoded>
			<wfw:commentRss>http://www.eahanson.com/2007/10/16/a-ruby-script-to-concatenate-and-compress-javascript-files/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Big New Feature In JsUnit 2.2 alpha 25</title>
		<link>http://www.eahanson.com/2007/08/13/big-new-feature-in-jsunit-22-alpha-25/</link>
		<comments>http://www.eahanson.com/2007/08/13/big-new-feature-in-jsunit-22-alpha-25/#comments</comments>
		<pubDate>Mon, 13 Aug 2007 08:21:33 +0000</pubDate>
		<dc:creator>Erik</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[JsUnit]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://www.eahanson.com/2007/08/13/big-new-feature-in-jsunit-22-alpha-25/</guid>
		<description><![CDATA[In order to run all test functions in a test page, JsUnit naturally needs to know what those test functions are. It's able to get a list of those functions from Firefox, Safari and Opera, but it's not able to get them from Internet Explorer. So in IE, JsUnit has to resort to searching the text of all scripts for strings that look like test function names. Unfortunately, it doesn't understand comments so commented-out test functions will end up running anyway. ]]></description>
			<content:encoded><![CDATA[<p>In order to run all test functions in a test page, <a href="http://www.jsunit.net/">JsUnit</a> naturally needs to know what those test functions are. It&#8217;s able to get a list of those functions from Firefox, Safari and Opera, but it&#8217;s not able to get them from Internet Explorer. </p>
<p>So in IE, JsUnit has to resort to searching the text of all scripts for strings that look like test function names. Unfortunately, it doesn&#8217;t understand comments so commented-out test functions will end up running anyway. </p>
<p>Recently, Dean McNamee and <a href="http://pupius.co.uk/">Dan Pupius</a> alerted <a href="http://edwardh.com/">Edward Hieatt</a> and me to an undocumented Internet Explorer Javascript function called <tt>RuntimeObject</tt> and suggested JsUnit might be able to use it to discover test functions. </p>
<p>I replaced the text searching with <tt>RuntimeObject</tt> and tagged it as version 2.2 alpha 25. (I also added an <tt>assertEqualsIgnoringOrder</tt> function while I was making changes.)</p>
<p>Browse the new version <a href="http://jsunit.svn.sourceforge.net/viewvc/jsunit/tags/v2_2alpha25/jsunit/">at SourceForge</a> or check it out like this:</p>
<div class="code">svn co https://jsunit.svn.sf.net/svnroot/jsunit/tags/v2_2alpha25/jsunit/ jsunit</div>
<p>Try it out and <a href="http://tech.groups.yahoo.com/group/jsunit/">let us know</a> if there are any problems.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.eahanson.com/2007/08/13/big-new-feature-in-jsunit-22-alpha-25/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Minor New Features In JsUnit 2.2alpha24</title>
		<link>http://www.eahanson.com/2007/08/09/minor-new-features-in-jsunit-22alpha24/</link>
		<comments>http://www.eahanson.com/2007/08/09/minor-new-features-in-jsunit-22alpha24/#comments</comments>
		<pubDate>Fri, 10 Aug 2007 01:46:36 +0000</pubDate>
		<dc:creator>Erik</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[JsUnit]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://www.eahanson.com/2007/08/09/minor-new-features-in-jsunit-22alpha24/</guid>
		<description><![CDATA[I added a few new features to JsUnit and tagged it as version 2.2 alpha 24: new log button, new URL parameters, and easier suite creation.]]></description>
			<content:encoded><![CDATA[<p>I added a few new features to <a href="http://jsunit.net">JsUnit</a> and tagged it as version 2.2 alpha 24. Browse the new version <a href="http://jsunit.svn.sourceforge.net/viewvc/jsunit/tags/v2_2alpha24/jsunit/">at SourceForge</a> or check it out like this:</p>
<div class="code">
  svn co https://jsunit.svn.sf.net/svnroot/jsunit/tags/v2_2alpha24/jsunit/ jsunit
</div>
<h3>Show Log</h3>
<p>There&#8217;s now a &#8220;Show Log&#8221; button that opens a window with a log of what JsUnit has been up to.</p>
<p><a href="http://www.eahanson.com/weblog/wp-content/uploads/2007/08/testrunner.jpg" title="New Log Button"><img src="http://www.eahanson.com/weblog/wp-content/uploads/2007/08/testrunner.thumbnail.jpg" alt="New Log Button" /></a></p>
<p>New log button (click image for larger view)</p>
<p><a href="http://www.eahanson.com/weblog/wp-content/uploads/2007/08/log.gif" title="New Log Window"><img src="http://www.eahanson.com/weblog/wp-content/uploads/2007/08/log.thumbnail.gif" alt="New Log Window" /></a></p>
<p>New log window (click image for larger view)</p>
<h3>New URL Parameters</h3>
<p>There are three new URL parameters:</p>
<ul>
<li><tt>suppressDialogs=true</tt> will suppress JsUnit&#8217;s dialogs in interactive mode</li>
<li><tt>setupPageTimeout=<em>n</em></tt> will change the timeout for the setupPage call</li>
<li><tt>pageLoadTimeout=<em>n</em></tt> will change the page load timeout</li>
</ul>
<h3>Easier Suite Creation</h3>
<p>The <tt>jsUnitTestSuite</tt> constructor now accepts test pages and subsuites as parameters. So instead of this:</p>
<pre>
function suite() {
  var suite = new jsUnitTestSuite();
  suite.addTestPage("/foo/barTest.html");
  suite.addTestPage("/foo/bazTest.html");
  return suite;
}</pre>
<p>you can do this:</p>
<pre>
function suite() {
  return new jsUnitTestSuite("/foo/barTest.html", "/foo/bazTest.html");
}</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.eahanson.com/2007/08/09/minor-new-features-in-jsunit-22alpha24/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A Ruby Script To Generate a JsUnit Suite</title>
		<link>http://www.eahanson.com/2007/05/26/a-ruby-script-to-generate-a-jsunit-suite/</link>
		<comments>http://www.eahanson.com/2007/05/26/a-ruby-script-to-generate-a-jsunit-suite/#comments</comments>
		<pubDate>Sat, 26 May 2007 20:38:29 +0000</pubDate>
		<dc:creator>Erik</dc:creator>
				<category><![CDATA[Howto]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[JsUnit]]></category>

		<guid isPermaLink="false">http://www.eahanson.com/weblog/?p=16</guid>
		<description><![CDATA[I've got a bunch of JsUnit tests for a project I'm working on and I wanted an easy way to create a JsUnit suite that can run all the tests but also run any individual test page. Also, I wanted to be able to view any test page so I could debug the tests with Firebug. I also didn't want to run a web server all the time, so I wanted a script that would create a static HTML file.]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve got a bunch of JsUnit tests for a project I&#8217;m working on and I wanted an easy way to create a JsUnit suite that can run all the tests but also run any individual test page.</p>
<p>Also, I wanted to be able to view any test page so I could debug the tests with Firebug (as explained <a href="http://www.eahanson.com/weblog/?p=11">here</a>).</p>
<p>I also didn&#8217;t want to run a web server all the time, so I wanted a script that would create a static HTML file.</p>
<p>Here&#8217;s what I came up with. It&#8217;s not configurable, so you&#8217;ll have to modify it for your own needs.</p>
<p align="center"><strong><a href="/code/JsUnitSuiteBuilder.rb">JsUnitSuiteBuilder.rb</a></strong></p>
]]></content:encoded>
			<wfw:commentRss>http://www.eahanson.com/2007/05/26/a-ruby-script-to-generate-a-jsunit-suite/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Element.stylize via Prototype.js</title>
		<link>http://www.eahanson.com/2007/05/25/elementstylize-via-prototypejs/</link>
		<comments>http://www.eahanson.com/2007/05/25/elementstylize-via-prototypejs/#comments</comments>
		<pubDate>Fri, 25 May 2007 20:13:18 +0000</pubDate>
		<dc:creator>Erik</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Web development]]></category>

		<guid isPermaLink="false">http://www.eahanson.com/weblog/?p=15</guid>
		<description><![CDATA[I often want to add a bunch of styles to an element, so I wrote a simple stylize method.]]></description>
			<content:encoded><![CDATA[<p>I often want to add a bunch of styles to an element, so I wrote a <tt>stylize</tt> method so I can do something like this:</p>
<pre>
$("foo").stylize({
  color: red,
  background-color: green,
  text-decoration: underline
});</pre>
<p>Implementing <tt>stylize</tt> is easy with <a href="http://prototypejs.org/">Prototype</a>&#8216;s <a href="http://prototypejs.org/api/element/addMethods">Element.addMethods()</a> method:</p>
<pre>
var ElementExtensions = {
  stylize: function(element, styles) {
    for (var s in styles) {
      element.style[s] = styles[s];
    }
    return element;
  }
}
Element.addMethods(ElementExtensions);</pre>
<p><b>Update:</b> <a href="http://prototypejs.org/2007/8/15/prototype-1-6-0-release-candidate">Prototype 1.6</a> added a similar <tt>setStyle</tt> method which works similarly but also allows CSS string-type style declaration (e.g., <tt>myElement.setStyle("color: blue; border: 3px")</tt>). Still, the above is a nice example of <tt>Element.addMethods()</tt>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.eahanson.com/2007/05/25/elementstylize-via-prototypejs/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Debugging a JsUnit Test With Firebug</title>
		<link>http://www.eahanson.com/2006/11/16/debugging-a-jsunit-test-with-firebug/</link>
		<comments>http://www.eahanson.com/2006/11/16/debugging-a-jsunit-test-with-firebug/#comments</comments>
		<pubDate>Thu, 16 Nov 2006 07:36:53 +0000</pubDate>
		<dc:creator>Erik</dc:creator>
				<category><![CDATA[Howto]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[JsUnit]]></category>

		<guid isPermaLink="false">http://www.eahanson.com/weblog/?p=11</guid>
		<description><![CDATA[Sometimes I find that I want to debug a JsUnit test because I'm not quite sure what's going on in the browser. FireBug has a nice debugger, but I couldn't get it to work with the JsUnit test runner. I could set breakpoints in JsUnit itself, but any breakpoints in my test would be ignored. And then it hit me: ditch the test runner.]]></description>
			<content:encoded><![CDATA[<p>Sometimes I find that I want to debug a <a href="http://www.jsunit.net/">JsUnit</a> test because I&#8217;m not quite sure what&#8217;s going on in the browser.</p>
<p><a href="http://getfirebug.com/">FireBug</a> has a nice debugger, but I couldn&#8217;t get it to work with the JsUnit test runner. I could set breakpoints in JsUnit itself, but any breakpoints in my test would be ignored.</p>
<p>And then it hit me: ditch the test runner. I opened my test page directly in Firefox, opened FireBug, clicked the Debugger tab, and chose my test from the &#8220;Scripts&#8221; menu. Here&#8217;s a simplified version:</p>
<pre>
function testUpdate() {
  var listPanel = new ListPanel();
  listPanel.update(["one", "two", "three"]);

  var children = $("content").childNodes;
  assertEquals("one", children[0]);
  assertEquals("two", children[1]);
  assertEquals("three", children[2]);
}</pre>
<p>I put a breakpoint at the first <tt>assertEquals</tt> and switched to the Console tab and typed <tt>testUpdate()</tt>. I saw the ListPanel getting drawn in the browser (something you don&#8217;t see in the JsUnit test runner) and in the Debugger tab I could inspect all my variables.</p>
<p>But even better, I could go back to the Console tab and start evaluating Javascript.</p>
<pre>
&gt;&gt;&gt; children.length
3</pre>
<p>Good.</p>
<pre>
&gt;&gt;&gt; children[0]
div</pre>
<p>Bad.</p>
<pre>
&gt;&gt;&gt; children[0].firstChild
[Text] "one"</pre>
<p>Better.</p>
<pre>
&gt;&gt;&gt; children[0].firstChild.nodeValue
"one"</pre>
<p>Perfect.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.eahanson.com/2006/11/16/debugging-a-jsunit-test-with-firebug/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Setting XSL Parameters from Javascript in AJAXSLT</title>
		<link>http://www.eahanson.com/2005/10/23/setting-xsl-parameters-from-javascript-in-ajaxslt/</link>
		<comments>http://www.eahanson.com/2005/10/23/setting-xsl-parameters-from-javascript-in-ajaxslt/#comments</comments>
		<pubDate>Sun, 23 Oct 2005 23:34:22 +0000</pubDate>
		<dc:creator>Erik</dc:creator>
				<category><![CDATA[Howto]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[XSL]]></category>

		<guid isPermaLink="false">http://www.eahanson.com/weblog/?p=6</guid>
		<description><![CDATA[Recently, I was trying to pass some info from my Javascript into my XSL stylesheet. Here's how I finally did it.]]></description>
			<content:encoded><![CDATA[<p>Google&#8217;s <a href="http://goog-ajaxslt.sourceforge.net/">AJAXSLT</a> library is very nice, but it is lacking in documentation and sometimes hard to figure out.</p>
<p>
Recently, I was trying to pass some info from my Javascript into my XSL stylesheet. Here&#8217;s how I finally did it:</p>
<p>
<i>(Quick note: in real life, I don&#8217;t name variables &quot;myThis&quot; and &quot;myThat&quot;; I&#8217;m just doing it here to make it clear what is my code and what is part of XSL, AJAXSLT, Javascript, etc.)</i></p>
<p><h4>The XSL</h4>
<pre>
&lt;xsl:stylesheet version=&quot;1.0&quot;
    xmlns:xsl=&quot;http://www.w3.org/1999/XSL/Transform&quot;&gt;
  &lt;xsl:param name=&quot;myParam&quot; select=&quot;&apos;myDefault&apos;&quot;/&gt;
  &lt;xsl:template match=&quot;/&quot;&gt;
    myParam: &lt;xsl:value-of select=&quot;$myParam&quot;/&gt;
  &lt;/xsl:template&gt;
&lt;/xsl:stylesheet&gt;
</pre>
<p><h4>The Javascript</h4>
<pre>
var myContext = new ExprContext(myXml);
myContext.setVariable(&quot;myParam&quot;,
    <b>new StringValue(&quot;the value for myParam&quot;)</b>);
xsltProcessContext(myContext, myXsl, myRootElement);
</pre>
<h4>The Trick</h4>
<p>So the big trick, which I figured out after reading lots of the AJAXSLT code, was to set the parameter to a <tt>StringValue</tt>, rather than a regular Javascript String. <tt>StringValue</tt> is part of AJAXSLT. <b>Update:</b> Will, in the comments below, mentions that there are four total types: <tt>StringValue</tt>, <tt>NumberValue</tt>, <tt>BooleanValue</tt> and <tt>NodeSetValue</tt>.</p>
<h4>Troubleshooting</h4>
<p>Don&#8217;t forget to declare your parameter with <code>&lt;xsl:param.../&gt;</code> before using it with <code>&lt;xsl:value-of select=&quot;$...&quot;/&gt;</code>, otherwise Ajaxslt will blow up in the middle of rendering.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.eahanson.com/2005/10/23/setting-xsl-parameters-from-javascript-in-ajaxslt/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>A Mac OS X Web Browser for JavaScript Testing</title>
		<link>http://www.eahanson.com/2005/10/02/writing-a-mac-os-x-web-browser-for-javascript-testing/</link>
		<comments>http://www.eahanson.com/2005/10/02/writing-a-mac-os-x-web-browser-for-javascript-testing/#comments</comments>
		<pubDate>Sun, 02 Oct 2005 21:34:22 +0000</pubDate>
		<dc:creator>Erik</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[My Software]]></category>

		<guid isPermaLink="false">http://www.eahanson.com/weblog/?p=5</guid>
		<description><![CDATA[I was playing with a very JavaScript-heavy web page and wanted my automated tests to use a real web browser. I tried running them inside Safari, but it's a bit annoying to have my tests take control of my browser. Plus, there were caching issues. So I wrote a very simple web browser.]]></description>
			<content:encoded><![CDATA[<p>I was playing with a very JavaScript-heavy web page and wanted my automated tests to use a real web browser. I tried running them inside Safari, but it&#8217;s a bit annoying to have my tests take control of my browser. Plus, there were caching issues. So I wrote a very simple web browser with the following features:</p>
<ul>
<li>It uses WebKit so it works just like Safari</li>
<li>It doesn&#8217;t do any caching</li>
<li>It takes a URL command-line parameter and loads it</li>
<li>It quits immediately <b>[update: I added a noquit paramter in case you don't want it to quit immediately]</b></li>
</ul>
<p>It currently has the following problems:</p>
<ul>
<li>It&#8217;s uses AppKit, so it has a UI. I really wanted it to be a command-line-only app, but I haven&#8217;t yet figured out how to do that</li>
<li>Invoking it is painful: <tt>/Applications/wkget.app/Contents/MacOS/wkget -url http://www.apple.com</tt></li>
<li>It only tests WebKit; one day I might make a version that uses Firefox&#8217;s JavaScript engine</li>
</ul>
<p>I called it <b>wkget</b> and you can <a href="/sw/wkget.zip">download it here</a>. [<b>Update:</b> I had an incorrectly-built version up here for a while. It's fixed now.]</p>
<p>Here&#8217;s the code (sorry for the formatting; I had to wrap everything for this very narrow column):</p>
<pre>
@implementation WkgetController
- (void)awakeFromNib {
  [self gotoUrl:self];
  [webView setFrameLoadDelegate:self];
}

- (IBAction)gotoUrl:(id)sender {
  NSString *url = [[NSUserDefaults standardUserDefaults]
      stringForKey:@"url"];

  if (url == nil) {
    url = @"http://www.apple.com/";
  }

  NSURLRequest *request = [NSURLRequest
      requestWithURL:[NSURL URLWithString:url]
      cachePolicy:NSURLRequestReloadIgnoringCacheData
      timeoutInterval:1.0];

  [[webView mainFrame] loadRequest:request];
}

- (void)webView:(WebView *)sender
  didFinishLoadForFrame:(WebFrame *)frame {
  if (![[NSUserDefaults standardUserDefaults]
      boolForKey:@"noquit"]) {
    [NSApp terminate:self];
  }
}
@end
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.eahanson.com/2005/10/02/writing-a-mac-os-x-web-browser-for-javascript-testing/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>How To Use Google&#8217;s Ajaxslt Library</title>
		<link>http://www.eahanson.com/2005/09/30/how-to-use-googles-ajaxslt-library/</link>
		<comments>http://www.eahanson.com/2005/09/30/how-to-use-googles-ajaxslt-library/#comments</comments>
		<pubDate>Fri, 30 Sep 2005 15:53:48 +0000</pubDate>
		<dc:creator>Erik</dc:creator>
				<category><![CDATA[Howto]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[XSL]]></category>

		<guid isPermaLink="false">http://www.eahanson.com/weblog/?p=4</guid>
		<description><![CDATA[Google has written an open-source library called Ajaxslt that implements XPath and XSLT in Javascript. It took a bit of playing to get it to work.]]></description>
			<content:encoded><![CDATA[<p><a href="http://search.yahoo.com/search?p=google&#038;sm=Yahoo%21+Search&#038;fr=FP-tab-web-t&#038;toggle=1&#038;cop=&#038;ei=UTF-8">Google</a> has written an open-source library called <a href="http://goog-ajaxslt.sourceforge.net/">Ajaxslt</a> that implements <a href="http://www.w3.org/TR/1999/REC-xpath-19991116">XPath</a> and <a href="http://www.w3.org/TR/1999/REC-xslt-19991116">XSLT</a> in Javascript.</p>
<p>It took a bit of playing to get it to work. Here&#8217;s some sample code. (I forgot to write it up when I did it, so I might have left something out.)</p>
<h3>Setup</h3>
<p>First, include the scripts. <b>Note:</b> make sure to have a closing <tt>&lt;/script&gt;</tt> tag rather than doing <tt>&lt;script ... /&gt;</tt> because that silently fails on some browsers (yay!).</p>
<pre>
&lt;!-- AJAXSLT --&gt;
&lt;script src=&quot;/ajaxslt/misc.js&quot;
    type=&quot;text/javascript&quot;&gt;&lt;/script&gt;

&lt;script src=&quot;/ajaxslt/dom.js&quot;
    type=&quot;text/javascript&quot;&gt;&lt;/script&gt;

&lt;script src=&quot;/ajaxslt/xpath.js&quot;
    type=&quot;text/javascript&quot;&gt;&lt;/script&gt;

&lt;script src=&quot;/ajaxslt/xslt.js&quot;
    type=&quot;text/javascript&quot;&gt;&lt;/script&gt;

&lt;script src=&quot;/ajaxslt/xpathdebug.js&quot;
    type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
</pre>
<h3>Using Ajaxslt for XSL Transformation</h3>
<p>For XSL transformation, you&#8217;ll need three things: some XML, some XSL, and a node (or DocumentFragment presumably) to place the result in. One way to get the XML and XSL is to load them through an XmlHttpRequest. Ajaxslt also provides a couple of handy functions to convert between text and XML:</p>
<pre>
var myText = &quot;...&quot;;
var myXml = xmlParse(myText);
var myTextAgain = xmlText(myXml);
</pre>
<p>Once you&#8217;ve got the XML and XSL, you&#8217;re ready to do the transformation:</p>
<pre>
var myNode = document.getElementById(&quot;myId&quot;);
xsltProcessContext(new ExprContext(myXml), myXsl, myNode);
</pre>
<p>Your node should now contain the result of the transformation.</p>
<h3>Using Ajaxslt for XPath</h3>
<p>You can also use Ajaxslt for XPath evaluation, which is really handy when writing tests on your rendered document:</p>
<pre>
var expr = xpathParse(myXpathString);
var result = expr.evaluate(new ExprContext(myXmlDocument));
var resultAsString = result.stringValue();
</pre>
<h3>Troublshooting</h3>
<p><b>The order of the JavaScript include statements matters:</b> if Ajaxslt is giving strange errors, make sure the scripts are included in the exact same order as  in the Setup section of this page.</p>
<p><b>Make sure you know what you&#8217;re passing to Ajaxslt:</b> if you&#8217;re sending <tt>request.responseXML</tt> to a method, don&#8217;t look at <tt>request.responseText</tt> to see what you&#8217;re passing; use <tt>xmlText(request.responseXML)</tt>.</p>
<p><b>The root element isn&#8217;t selectable:</b> if your XML is <tt>&lt;foo id=&quot;myId&quot;&gt;...&lt;/foo&gt;</tt>, then  you don&#8217;t select foo&#8217;s id with <tt>/foo/@id</tt> but rather with just <tt>@id</tt>.</p>
<p><b>Case matters in xpath:</b> If you&#8217;re evaluating an xpath expression on an HTML DOM, note that the node names are most likely uppercase. So do <tt>/HTML/BODY</tt> instead of <tt>/html/body</tt></p>
]]></content:encoded>
			<wfw:commentRss>http://www.eahanson.com/2005/09/30/how-to-use-googles-ajaxslt-library/feed/</wfw:commentRss>
		<slash:comments>29</slash:comments>
		</item>
	</channel>
</rss>
