<?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>Otaqui.Com &#187; javascript</title>
	<atom:link href="http://otaqui.com/blog/tag/javascript/feed/" rel="self" type="application/rss+xml" />
	<link>http://otaqui.com/blog</link>
	<description>Pete Otaqui's blog about web development and everything else</description>
	<lastBuildDate>Fri, 11 May 2012 13:19:43 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	
		<item>
		<title>Sheaf &#8211; a little library for serial Promise management</title>
		<link>http://otaqui.com/blog/1217/sheaf-a-little-library-for-serial-promise-management/</link>
		<comments>http://otaqui.com/blog/1217/sheaf-a-little-library-for-serial-promise-management/#comments</comments>
		<pubDate>Sat, 24 Mar 2012 08:56:24 +0000</pubDate>
		<dc:creator>pete</dc:creator>
				<category><![CDATA[Professional]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://otaqui.com/blog/?p=1217</guid>
		<description><![CDATA[I&#8217;ve released sheaf, a library for looping over promises in a non-concurrent fashion. It helps you treat async operations as though they were synchronous instead (but doesn&#8217;t &#8220;block&#8221;). This is useful if you want to use a series of asynchronous functions on a list of initial items, but want one series to complete before the...  <a href="http://otaqui.com/blog/1217/sheaf-a-little-library-for-serial-promise-management/" class="more-link" title="Read Sheaf &#8211; a little library for serial Promise management">Read more &#187;</a>]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve released <a href="https://github.com/pete-otaqui/sheaf">sheaf</a>, a library for looping over promises in a non-concurrent fashion. It helps you treat async operations as though they were synchronous instead (but doesn&#8217;t &#8220;block&#8221;).</p>
<p>This is useful if you want to use a series of asynchronous functions on a list of initial items, but want one series to complete before the next one starts.</p>
<p><span id="more-1217"></span></p>
<p>The use case I had which prompted writing the library was loading results from a database, generating a jsdom page from each result, and taking a screenshot of each one. With 8000 results, I really didn&#8217;t want to try running them all concurrently, but since jsdom in asynchronous, I actually wanted to wait for each item to resolve before moving on to the next.</p>
<p>Sheaf is available via <a href="http://npmjs.org">npm</a>, and also works fine in browsers. It depends on <a href="https://github.com/pete-otaqui/bond">bond</a> to provide it&#8217;s returned promise.</p>
<p>The API looks like this:</p>
<pre class="brush: javascript">

var aList = [&#039;/one.json&#039;, &#039;/two.json&#039;]
var fn1Async = function() { /* return a promise */ }
var fn2Async = function() { /* return a promise */ }
var fn3Sync = function() { /* return a value */ }
var fn4Async = function() { /* return a promise */ }

sheaf( aList, fn1Async, fn2Async, fn3Sync, fn4Async );
</pre>
<p>The first argument to sheaf is the list of things you want to loop over.  Subsequent arguments are functions that either return promises or values.  The first such function is given each items from the array as sole argument, each function after that is given the return value (or promise resolution arguments) from the previous function as parameters.</p>
<p>Each complete cycle of the functions is run through before started again on the next member of the initial array.</p>
<p>A diagram might help:</p>
<img src="https://docs.google.com/drawings/pub?id=1TggGPBZUpjIygkfsE4A98Udc0Obx8wnjD-j4034z-Og&#038;w=619&#038;h=217" alt="Sheaf's flow" />
<p>Sheaf itself returns a promise, which will notify on each iteration and resolve when all iterations are complete, e.g.</p>
<pre class="brush: javascript">

sheaf( aList, fn1Async, fn2Async, fn3Sync, fn4Async )
  .progress(function() {console.log(&#039;one loop completed&#039;, arguments})
  .done(function(newList) {console.log(&#039;all loops completed&#039;, newList)});
</pre>
<p>Since sheaf and bond are designed to work with multiple arguments, the &#8220;newList&#8221; with which the promise is resolved will be an array of arrays (one per item in the initial aList);</p>
<p>Sheaf can be useful if you want to perform even a single async function over and over again but wait for completion each time before running again.  It&#8217;s main purpose though is to loop over asynchronous chains in a non-concurrent way.  You can imagine that trying to load 8000 URLs, create 8000 DOMs pages in memory and take 8000 screenshots all at once is not a very good idea!</p>
<p>However, you probably don&#8217;t want to use this if you are responding to HTTP calls, since you never know how long these operations will take.  It would make more sense to fire off a worker process, and then return much faster.</p>
<p>As I have the time I&#8217;ll be trying to write up some more examples for sheaf, so stay tuned.</p>
]]></content:encoded>
			<wfw:commentRss>http://otaqui.com/blog/1217/sheaf-a-little-library-for-serial-promise-management/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Bond &#8211; a simple Promises library, available with npm</title>
		<link>http://otaqui.com/blog/1190/bond-a-simple-promises-library-available-with-npm/</link>
		<comments>http://otaqui.com/blog/1190/bond-a-simple-promises-library-available-with-npm/#comments</comments>
		<pubDate>Sat, 24 Mar 2012 06:39:45 +0000</pubDate>
		<dc:creator>pete</dc:creator>
				<category><![CDATA[Professional]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://otaqui.com/blog/?p=1190</guid>
		<description><![CDATA[I&#8217;ve released bond &#8211; a simple Promises/A implementation. The only reasons to use this library rather than something like node-promise are that it can be used in a browser as well as nodejs, it supports multiple arguments for promise callbacks (this is actually why I wrote it) and it has a cool name. Bond installation is...  <a href="http://otaqui.com/blog/1190/bond-a-simple-promises-library-available-with-npm/" class="more-link" title="Read Bond &#8211; a simple Promises library, available with npm">Read more &#187;</a>]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve released <a href="https://github.com/pete-otaqui/bond">bond</a> &#8211; a simple Promises/A implementation. The only reasons to use this library rather than something like node-promise are that it can be used in a browser as well as nodejs, it supports multiple arguments for promise callbacks (this is actually why I wrote it) and it has a cool name.</p>
<p><span id="more-1190"></span></p>
<p>Bond installation is extremely easy with <a href="http://npmjs.org">npm</a> by adding it to your package.json file and executing &#8220;npm install&#8221;.</p>
<p>It provides two equivalent options for usage &#8220;new bond.Deferred()&#8221; or &#8220;bond.defer()&#8221;. This returns a deferred object with the usual methods:</p>
<ul>
<li>my_deferred.resolve(arg1, &#8230;, argN)</li>
<li>my_deferred.reject(arg1, &#8230;, argN)</li>
<li>my_deferred.notify(arg1, &#8230;, argN)</li>
<li>my_promise = my_deferred.promise() *</li>
<li>my_promise.then(successFn, failureFn, progressFn)</li>
<li>my_promise.done(successFn)</li>
<li>my_promise.fail(failureFn)</li>
<li>my_promise.progress(progressFn)</li>
</ul>
<p>* nb &#8211; providing &#8220;promise()&#8221; as a method rather than a property violates <a href="http://wiki.commonjs.org/wiki/Promises/A">the CommonJS Promises/A spec</a>, but I&#8217;ve seen it elsewhere and prefer it.</p>
]]></content:encoded>
			<wfw:commentRss>http://otaqui.com/blog/1190/bond-a-simple-promises-library-available-with-npm/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Simple Javascript Validator Library &#8211; Validator.js</title>
		<link>http://otaqui.com/blog/1076/simple-javascript-validator-library-validator-js/</link>
		<comments>http://otaqui.com/blog/1076/simple-javascript-validator-library-validator-js/#comments</comments>
		<pubDate>Sun, 14 Aug 2011 05:58:36 +0000</pubDate>
		<dc:creator>pete</dc:creator>
				<category><![CDATA[Professional]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[webdev]]></category>

		<guid isPermaLink="false">http://otaqui.com/blog/?p=1076</guid>
		<description><![CDATA[I had a need to do some data validation in javascript, and all the libraries I looked at seemed quite opinionated about *what* you were going to validate &#8211; i.e. form data &#8211; let alone the increase in server-side javascript in the last couple of years. My data wasn&#8217;t directly tied to a form, so...  <a href="http://otaqui.com/blog/1076/simple-javascript-validator-library-validator-js/" class="more-link" title="Read Simple Javascript Validator Library &#8211; Validator.js">Read more &#187;</a>]]></description>
			<content:encoded><![CDATA[<p>I had a need to do some data validation in javascript, and all the libraries I looked at seemed quite opinionated about *what* you were going to validate &#8211; i.e. form data &#8211; let alone the increase in server-side javascript in the last couple of years. My data wasn&#8217;t directly tied to a form, so it didn&#8217;t quite seem worthwhile trying to shoe horn my needs into what the libraries expected, and I could also see a need for a validation library that could be adapted for Node.</p>
<p>Enter <a href="https://pete-otaqui.github.com/Validator.js">Validator.js</a>.</p>
<p>Validator&#8217;s only dependency is on <a href="http://documentcloud.github.com/underscore.js">underscore.js</a> from Document Cloud.</p>
<p>Validator has two usage forms: the first for very quick and simple one-off cases:</p>
<pre class="brush: javascript">
// Simple use:
var result
result = Validator.isEmail(&#039;not_an_email&#039;);
console.log(result); // false
result = Validator.isEmail(&#039;joe@example.com&#039;);
console.log(result); // true
</pre>
<p>I found this on its own quite a lot more flexible than most of the form-driven libraries out there.  However, I also wanted to be able to create more complex sets of validations to run on a piece of data.  For that case, you create an instance of Validator and use it&#8217;s add() method:</p>
<pre class="brush: javascript">
var result,
    myValidator

myValidator = new Validator();

myValidator.add(&#039;unique&#039;);
myValidator.add(&#039;minLength&#039;, 6);

result = myValidator.validate( [1, 2, 3, 4, 5, 6, 6] );
console.log(result); // false, the array is long enough but contains non-unique members
</pre>
<p>This got me a fair bit closer to what I wanted, but you don&#8217;t know which part failed, so it&#8217;s harder to give reasonable feedback. I added a set of error messages to validator instances which gets populated after a call to validate():</p>
<pre class="brush: javascript">
var result,
    myValidator

myValidator = new Validator();

myValidator.add(&#039;unique&#039;);
myValidator.add(&#039;minLength&#039;, 6);
myValidator.add(&#039;maxLength&#039;, 8);

result = myValidator.validate( [1, 2, 3, 4, 5, 6, 6, 8, 9, 10] );
console.log(result); // false, the array is long enough but contains non-unique members
console.log(myValidator.errors);
/*
myValidator.errors == [
    &#039;The list must be made up of unique items&#039;,
    &#039;The list is too long&#039;
]
*/
</pre>
<p>Again, this is pretty good but even though Validator supports adding messages in any language you want and falling back (by default) to English (see the source code), default error messages still aren&#8217;t always what you need.  I also added the ability to set a custom error message per &#8220;validation&#8221;.</p>
<pre class="brush: javascript">
var result,
    myValidator

myValidator = new Validator();

myValidator.add(&#039;unique&#039;).message(&#039;You are repeating yourself&#039;);
myValidator.add(&#039;minLength&#039;, 6).message(&#039;Too tiny!&#039;);
myValidator.add(&#039;maxLength&#039;, 8).message(&#039;Too bloated!&#039;);

result = myValidator.validate( [1, 2, 3, 4, 5, 6, 6, 8, 9, 10] );
console.log(result); // false, the array is long enough but contains non-unique members
console.log(myValidator.errors);
/*
myValidator.errors == [
    &#039;You are repeating yourself&#039;,
    &#039;Too bloated!&#039;
]
*/
</pre>
<p>You can also chain calls to add() and message():</p>
<pre class="brush: javascript">
var result,
    myValidator

myValidator = new Validator();

myValidator.add(&#039;unique&#039;).message(&#039;You are repeating yourself&#039;)
    .add(&#039;minLength&#039;, 6).message(&#039;Too tiny!&#039;)
    .add(&#039;maxLength&#039;, 8).message(&#039;Too bloated!&#039;);
</pre>
<p>I&#8217;ve added some code which should make it easy to use this as a CommonJS AMD javascript module.  In it&#8217;s default form you can just include it with a script tag.</p>
<p>If you&#8217;re interested in developing Validator itself, the project is tested with <a href="http://pivotal.github.com/jasmine/">Jasmine</a> and documented with <a href="http://code.google.com/p/jsdoc-toolkit/">JSDoc</a>.  Both of these can be run with Rake, and the easiest way to get setup is to use <a href="http://gembundler.com/">Bundler</a>.  Once you&#8217;ve got the dependencies you get three rake tasks:</p>
<pre class="brush: bash">
# Start the jasmine server, and open http://localhost:8888/ to run the test suite:
$ rake jasmine
# Start the jasmine server and also run a browser through the tests automatically:
$ rake jasmine:ci
# Generate the docs
$ rake jsdoc
</pre>
<p>If you fork the project and add any more validations, please also add tests and docs.</p>
]]></content:encoded>
			<wfw:commentRss>http://otaqui.com/blog/1076/simple-javascript-validator-library-validator-js/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Testing remote (PHP) websites with Capybara, Cucumber, Mechanize, Selenium 2 Webdriver &#8230; and SauceLabs</title>
		<link>http://otaqui.com/blog/1072/testing-remote-php-websites-with-capybara-cucumber-mechanize-selenium-2-webdriver-and-saucelabs/</link>
		<comments>http://otaqui.com/blog/1072/testing-remote-php-websites-with-capybara-cucumber-mechanize-selenium-2-webdriver-and-saucelabs/#comments</comments>
		<pubDate>Thu, 11 Aug 2011 14:40:16 +0000</pubDate>
		<dc:creator>pete</dc:creator>
				<category><![CDATA[Professional]]></category>
		<category><![CDATA[capybara]]></category>
		<category><![CDATA[cucumber]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[testing]]></category>

		<guid isPermaLink="false">http://otaqui.com/blog/?p=1072</guid>
		<description><![CDATA[This is more or less the perfect setup for me, and it lets us run our tests against our PHP web application using the very fast mechanize driver where possible, and for tests that require javascript we can use either the &#8220;normal&#8221; selenium driver in capybara, or send the tests off to your local grid,...  <a href="http://otaqui.com/blog/1072/testing-remote-php-websites-with-capybara-cucumber-mechanize-selenium-2-webdriver-and-saucelabs/" class="more-link" title="Read Testing remote (PHP) websites with Capybara, Cucumber, Mechanize, Selenium 2 Webdriver &#8230; and SauceLabs">Read more &#187;</a>]]></description>
			<content:encoded><![CDATA[<p>This is more or less the perfect setup for me, and it lets us run our tests against our PHP web application using the very fast mechanize driver where possible, and for tests that require javascript we can use either the &#8220;normal&#8221; selenium driver in capybara, or send the tests off to your local grid, or even send them off to Sauce Labs where we want to cover more platforms and versions than we have setup locally.</p>
<p>https://gist.github.com/1139797</p>
<p><script src="https://gist.github.com/1139797.js"> </script></p>
<p>Next step &#8230; running the tests in parallel!</p>
]]></content:encoded>
			<wfw:commentRss>http://otaqui.com/blog/1072/testing-remote-php-websites-with-capybara-cucumber-mechanize-selenium-2-webdriver-and-saucelabs/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Building Conway&#8217;s Game of Life in Javascript</title>
		<link>http://otaqui.com/blog/1020/building-conways-game-of-life-in-javascript/</link>
		<comments>http://otaqui.com/blog/1020/building-conways-game-of-life-in-javascript/#comments</comments>
		<pubDate>Tue, 02 Aug 2011 12:00:06 +0000</pubDate>
		<dc:creator>pete</dc:creator>
				<category><![CDATA[Professional]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[webdev]]></category>

		<guid isPermaLink="false">http://otaqui.com/blog/?p=1020</guid>
		<description><![CDATA[As part of an interesting exercise at work, I built an implementation of Conway&#8217;s Game Of Life in Javascript. If you haven&#8217;t come across the Game Of Life, it&#8217;s really quite interesting and worth looking at. My colleagues also made variations, including canvas-based and Web GL 3 dimensional (there was even discussion about n-dimensional, with...  <a href="http://otaqui.com/blog/1020/building-conways-game-of-life-in-javascript/" class="more-link" title="Read Building Conway&#8217;s Game of Life in Javascript">Read more &#187;</a>]]></description>
			<content:encoded><![CDATA[<p>As part of an interesting exercise at work, I built an implementation of <a href="http://en.wikipedia.org/wiki/Conway%27s_Game_of_Life">Conway&#8217;s Game Of Life</a> in Javascript.  If you haven&#8217;t come across the Game Of Life, it&#8217;s really quite interesting and worth looking at.  My colleagues also made variations, including canvas-based and Web GL 3 dimensional (there was even discussion about n-dimensional, with sliders to view the 4th, 5th and further dimensions).  My particular take was to make the game space &#8220;infinite&#8221; rather than a fixed grid.</p>
<p>It&#8217;s not really infinite of course, I haven&#8217;t made any attempt to have a position greater than Number.MAX_VALUE.  The real point is that it is possible to have a huge playing area, and only the living &#038; possibly-living-next-round cells are taken into account.</p>
<p>I avoided using any ready-made frameworks, in part so that it could be transported to the server-side on top of something like <a href="http://nodejs.org">NodeJS</a> &#8211; I was imagining a multi-player game where each user could &#8220;paint&#8221; cells onto the canvas, and maybe even that next-generation cells would take an identifier from their parents, letting people &#8220;fight&#8221;.  I haven&#8217;t really got the time for that at the moment, but it seemed a nice idea.</p>
]]></content:encoded>
			<wfw:commentRss>http://otaqui.com/blog/1020/building-conways-game-of-life-in-javascript/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Getting a reference to an unselected radiobutton (using jQuery)</title>
		<link>http://otaqui.com/blog/1033/getting-a-reference-to-an-unselected-radiobutton-using-jquery/</link>
		<comments>http://otaqui.com/blog/1033/getting-a-reference-to-an-unselected-radiobutton-using-jquery/#comments</comments>
		<pubDate>Tue, 02 Aug 2011 11:59:09 +0000</pubDate>
		<dc:creator>pete</dc:creator>
				<category><![CDATA[Professional]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://otaqui.com/blog/?p=1033</guid>
		<description><![CDATA[The &#8220;change&#8221; event on a radiobutton input only fires when it becomes selected. If you want to trigger some behaviour on an unselected radiobutton, then you have to bind to the change event of the radiogroup, which you can do like so: &#60;ul&#62; &#60;li&#62; &#60;input id=&#34;r1&#34; name=&#34;something&#34; type=&#34;radio&#34; value=&#34;basic&#34; /&#62; &#60;label for=&#34;r1&#34;&#62;Basic&#60;/label&#62; &#60;/li&#62; &#60;li&#62; &#60;input...  <a href="http://otaqui.com/blog/1033/getting-a-reference-to-an-unselected-radiobutton-using-jquery/" class="more-link" title="Read Getting a reference to an unselected radiobutton (using jQuery)">Read more &#187;</a>]]></description>
			<content:encoded><![CDATA[<p>The &#8220;change&#8221; event on a radiobutton input only fires when it becomes selected.  If you want to trigger some behaviour on an unselected radiobutton, then you have to bind to the change event of the radiogroup, which you can do like so:</p>
<pre class="brush: html">
&lt;ul&gt;
  &lt;li&gt;
    &lt;input id=&quot;r1&quot; name=&quot;something&quot; type=&quot;radio&quot; value=&quot;basic&quot; /&gt;
    &lt;label for=&quot;r1&quot;&gt;Basic&lt;/label&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;input id=&quot;r2&quot; name=&quot;something&quot; type=&quot;radio&quot; value=&quot;standard&quot; /&gt;
    &lt;label for=&quot;r2&quot;&gt;Standard&lt;/label&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;input id=&quot;r3&quot; name=&quot;something&quot; type=&quot;radio&quot; value=&quot;advanced&quot; /&gt;
    &lt;label for=&quot;r3&quot;&gt;Advanced&lt;/label&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;script&gt;
$(&quot;input[name=&#039;inputName&#039;]&quot;).change(function(ev) {

});
&lt;/script&gt;
</pre>
]]></content:encoded>
			<wfw:commentRss>http://otaqui.com/blog/1033/getting-a-reference-to-an-unselected-radiobutton-using-jquery/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Javascript EventEmitter Redux, now on github</title>
		<link>http://otaqui.com/blog/1025/javascript-eventemitter-redux-now-on-github/</link>
		<comments>http://otaqui.com/blog/1025/javascript-eventemitter-redux-now-on-github/#comments</comments>
		<pubDate>Tue, 11 Jan 2011 14:37:00 +0000</pubDate>
		<dc:creator>pete</dc:creator>
				<category><![CDATA[Professional]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://otaqui.com/blog/?p=1025</guid>
		<description><![CDATA[I&#8217;ve added some more features to the EventEmitter mixin (like actually working listener removal) and posted it to github: EventEmitter on github It&#8217;s fairly simple to use &#8230; something like this: var MyKlass = function() {}; EventEmitter.augment(MyKlass.prototype); /** * Show me * * @fires shown */ MyKlass.prototype.showMe = function() { this.trigger(&#039;shown&#039;, {&#039;visible&#039;:true}); } var myInstance...  <a href="http://otaqui.com/blog/1025/javascript-eventemitter-redux-now-on-github/" class="more-link" title="Read Javascript EventEmitter Redux, now on github">Read more &#187;</a>]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve added some more features to the EventEmitter mixin (like actually working listener removal) and posted it to github:</p>
<p><a href="https://github.com/pete-otaqui/EventEmitter">EventEmitter on github</a></p>
<p>It&#8217;s fairly simple to use &#8230; something like this:</p>
<pre class="brush: javascript">
var MyKlass = function() {};
EventEmitter.augment(MyKlass.prototype);

/**
 * Show me
 *
 * @fires shown
 */
MyKlass.prototype.showMe = function() {
  this.trigger(&#039;shown&#039;, {&#039;visible&#039;:true});
}

var myInstance = new MyKlass();
myInstance.on(&#039;shown&#039;, function(e) {
  console.log(e.visible);
}
myInstance.showMe();
</pre>
]]></content:encoded>
			<wfw:commentRss>http://otaqui.com/blog/1025/javascript-eventemitter-redux-now-on-github/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Started work on jQuery UI Modal widget</title>
		<link>http://otaqui.com/blog/919/started-work-on-jquery-ui-modal-widget/</link>
		<comments>http://otaqui.com/blog/919/started-work-on-jquery-ui-modal-widget/#comments</comments>
		<pubDate>Wed, 13 Oct 2010 14:26:49 +0000</pubDate>
		<dc:creator>pete</dc:creator>
				<category><![CDATA[Professional]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[webdev]]></category>

		<guid isPermaLink="false">http://otaqui.com/blog/?p=919</guid>
		<description><![CDATA[I&#8217;ve started working a jQuery UI Modal widget, for use in a project built on top of the widget library. We have very high accessibility standards, and the current &#8220;{modal:true}&#8221; option for the dialog widget unfortunately wasn&#8217;t as good as we needed. Seeing that the team had identified the need for a standalone Modal widget,...  <a href="http://otaqui.com/blog/919/started-work-on-jquery-ui-modal-widget/" class="more-link" title="Read Started work on jQuery UI Modal widget">Read more &#187;</a>]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve started working a jQuery UI Modal widget, for use in a project built on top of the widget library.</p>
<p>We have very high accessibility standards, and the current &#8220;{modal:true}&#8221; option for the dialog widget unfortunately wasn&#8217;t as good as we needed.  Seeing that the team had identified the need for <a href="http://wiki.jqueryui.com/Modal">a standalone Modal widget</a>, the team thought we could try and get the ball rolling.</p>
<p>You can see the work in progress here in <a href="http://github.com/pete-otaqui/jquery-ui/blob/master/ui/jquery.ui.modal.js">the modal widget in my fork of jquery ui</a>.</p>
<p>I&#8217;ve also been having <a href="http://forum.jquery.com/topic/refactoring-dialog-overlay-in-preparation-for-modal-better-keyboard-accessibility">a discssion about the modal widget</a> with Scott Gonzalez of the jQuery UI team.</p>
]]></content:encoded>
			<wfw:commentRss>http://otaqui.com/blog/919/started-work-on-jquery-ui-modal-widget/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>CSSP: Loading CSS with Javascript &#8211; and getting an onload callback.</title>
		<link>http://otaqui.com/blog/890/cssp-loading-css-with-javascript-and-getting-an-onload-callback/</link>
		<comments>http://otaqui.com/blog/890/cssp-loading-css-with-javascript-and-getting-an-onload-callback/#comments</comments>
		<pubDate>Tue, 28 Sep 2010 14:16:18 +0000</pubDate>
		<dc:creator>pete</dc:creator>
				<category><![CDATA[Professional]]></category>
		<category><![CDATA[dojo]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[webdev]]></category>

		<guid isPermaLink="false">http://otaqui.com/blog/?p=890</guid>
		<description><![CDATA[It seems fairly straightforward to require CSS with Javascript. The most obvious method that I thought of was creating a &#60;link&#62; tag and appending it to the head of the document. An alternative would be to load the text of the css file with an ajax XHR call, and then inject that into a &#60;style&#62;...  <a href="http://otaqui.com/blog/890/cssp-loading-css-with-javascript-and-getting-an-onload-callback/" class="more-link" title="Read CSSP: Loading CSS with Javascript &#8211; and getting an onload callback.">Read more &#187;</a>]]></description>
			<content:encoded><![CDATA[<p>It seems fairly straightforward to require CSS with Javascript.  The most obvious method that I thought of was creating a &lt;link&gt; tag and appending it to the head of the document. An alternative would be to load the text of the css file with an ajax XHR call, and then inject that into a &lt;style&gt; tag.</p>
<p>These are both fine for most cases, but what about a situation where you have a hard dependency on the css for the javascript to work correctly?  You could take a best-guess at a wait time for the CSS to load, or even set the XHR to be synchronous &#8211; however both of these are very poor for both actual and perceived performance of your page (and the former may simply fail).</p>
<p>When might this be the case?  Let&#8217;s say you have some asynchronously loaded javascript that is intended to create a widget on the page, something like this (which assumes you are using jQuery as your dom library):</p>
<pre class="brush: javascript">

function moveLargePanels() {
    // make a panel container for large panels
    $(&#039;&lt;div id=&quot;largePanelContainer&quot;&gt;&lt;/div&gt;&#039;)
        .appendTo(&#039;body&#039;);
    $(&#039;.panel&#039;).each( function(i, panel) {
        if ( panel.outerWidth() &gt; 300 ) {
            panel.appendTo(&#039;#largePanelContainer&#039;);
        }
    }
}
</pre>
<p>And some corresponding CSS:</p>
<pre class="brush: css">
.panel {
    border:1px solid #000;
    padding: 20px;
}
</pre>
<p>The idea here is that, since there is some interaction between the logic in the javascript (a test for the &#8220;outerWidth&#8221;) and the styling in the CSS (setting the padding) that the javascript can only work correctly once the CSS has been loaded and applied.</p>
<p>This should be fine right?  Start the javascript and the css loading, and have events attached to the load of each letting you know when everything is ready and it&#8217;s safe to fire &#8220;moveLargePanels()&#8221;.  Wrong, or at least tricky, and essentially impossible if the CSS is loaded from a different domain to the hosting webpage.</p>
<p>You can get James Burke&#8217;s excellent description of this problem here:<br />
<a href="http://requirejs.org/docs/faq-advanced.html#css">http://requirejs.org/docs/faq-advanced.html#css</a><br />
And a first pass at solving this (in some browsers) here:<br />
<a href="http://bugs.dojotoolkit.org/ticket/5402">http://bugs.dojotoolkit.org/ticket/5402</a></p>
<p>Burke mentions a using a &#8220;well known&#8221; style rule to test whether the style is loaded.  I suggest a standard pattern for the rule, and also a mechanism for dynamically setting it.</p>
<h2>Enter CSSP</h2>
<p>You may have heard of <a href="http://remysharp.com/2007/10/08/what-is-jsonp/">JsonP</a> &#8211; a way of serving dynamically generated JSON which is padded with a method call (the method name is supplied in the query string of the URL), which allows for cross domain loading of javascript.  The idea behind CSSP is similar &#8211; it defines a pattern for loading css cross domain.  Instead of wrapping in a callback though, we can use the URL query string mechanism to supply the special &#8220;test rule&#8221; that we use.</p>
<h3>Dynamic Rule Pattern</h3>
<p>Given this url:</p>
<p>http://someserver.com/stylefile.css?cssp=123456</p>
<pre class="brush: php">
.panel { ... }
.largePanelsContainer { .. }

/* and the special rule: */
cssp { zIndex:123456; }
</pre>
<p>So, in whatever loader we want to build, we can add something like this (n.b. this isn&#8217;t tested code):</p>
<pre class="brush: javascript">
var cssp_counter = 0;
function loadCss(url, callback, className, zIndex) {
    // create a counter for special class names, so they are unique
    className = className || &#039;cssp&#039; + (cssp_counter++);
    zIndex = zIndex || 123456;
    url = url + &#039;?&#039; + className + &#039;=&#039; + zIndex;
    $(&#039;&lt;link&gt;&#039;)
        .attr({
            rel: &quot;stylesheet&quot;,
            type: &quot;text/css&quot;,
            href: url
        .appendTo(&#039;head&#039;);
    // append a dummy div to the body for the test
    var div = $(&#039;&lt;div&gt;&lt;/div&gt;&#039;)
        .addClass(className)
        .appendTo(&#039;body&#039;);
    // now poll for the z-index value:
    var cssp_interval = setInterval( function() {
        // if the zIndex is applied, we know the css has loaded
        if ( div.css(&#039;zIndex&#039;) == zIndex ) {
            div.remove();
            // callback:
            callback();
            clearInterval( cssp_interval );
        }
    }, 100);

}
</pre>
<p>The code above to do the loading and fire a callback is very naive.  It would be much better to have an event that can have listeners added, and to have some tests and some failure management like a maximum timeout.</p>
<h3>Default Rule Pattern</h3>
<p>This obviously presupposes that the CSS is dynamically generated to some degree, even just by adding the special rule to an otherwise static file.  I think that an alternative to the performance-conscious would be a &#8220;default&#8221; special rule, based on the css filename.  This needs some thought, and could well be tied to a build-step in your deployment process (you do have one, right?).  The pattern comes in two parts:</p>
<ul>
<li>There is a standard zIndex that is always used.</li>
<li>The filename includes the &#8220;special class name&#8221; that is used within.</li>
</ul>
<p>For example:</p>
<p>Given the file: <strong>styles.fhddgso9j.css</strong></p>
<pre class="brush: css">
.someclass { ... }
.otherclass { ... }

/* and the special rule */
.fhddgso9j { z-index: 123456; }
</pre>
<p>The javascript to go alone with this might look something like:</p>
<pre class="brush: javascript">
var cssp_counter = 0;
function loadCss(url, callback) {
    // create a counter for special class names, so they are unique
    className = getSpecialClassName(url);
    zIndex = 123456;
    $(&#039;&lt;link&gt;&#039;)
        .attr({
            rel: &quot;stylesheet&quot;,
            type: &quot;text/css&quot;,
            href: url
        .appendTo(&#039;head&#039;);
    // append a dummy div to the body for the test
    var div = $(&#039;&lt;div&gt;&lt;/div&gt;&#039;)
        .addClass(className)
        .appendTo(&#039;body&#039;);
    // now poll for the z-index value:
    var cssp_interval = setInterval( function() {
        // if the zIndex is applied, we know the css has loaded
        if ( div.css(&#039;zIndex&#039;) == zIndex ) {
            div.remove();
            // callback:
            callback();
            clearInterval( cssp_interval );
        }
    }, 100);
}
function getSpecialClassName(url) {
  // get just the filename, e.g. &quot;styles.9ufosdfij.css&quot;
  var filename = url.substring( url.lastIndexOf(&#039;/&#039;)+1, url.length);
  // split on the &quot;.&quot; marks
  var parts = filename.split(&#039;.&#039;);
  // assume it will be the second-to-last part (since the last should be &quot;css&quot;)
  var className = parts[ parts.length-2 ];
  return className;
}
</pre>
<p>As noted above, this naive, untested code.</p>
<h2>Wrapping Up</h2>
<p>Ideally I&#8217;d like any &#8220;css loader&#8221; to use actual browser events (or properties) where possible, and to fallback on this setup as a last resort.</p>
<p>If I get time I&#8217;ll implement this and put the code on github.  Please do get in touch if you&#8217;d like to pair on this!</p>
]]></content:encoded>
			<wfw:commentRss>http://otaqui.com/blog/890/cssp-loading-css-with-javascript-and-getting-an-onload-callback/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>BBC Fisheye Greasemonkey Script</title>
		<link>http://otaqui.com/blog/646/bbc-fisheye-greasemonkey-script/</link>
		<comments>http://otaqui.com/blog/646/bbc-fisheye-greasemonkey-script/#comments</comments>
		<pubDate>Mon, 12 Apr 2010 09:15:08 +0000</pubDate>
		<dc:creator>pete</dc:creator>
				<category><![CDATA[Professional]]></category>
		<category><![CDATA[greasemonkey]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[webdev]]></category>

		<guid isPermaLink="false">http://otaqui.com/blog/?p=646</guid>
		<description><![CDATA[Greasemonkey script to reformat &#8220;Author&#8221; select elements on the BBC&#8217;s Fisheye repository browser, which are ridiculously long (because they contain a considerable chunk of certificate data) which messes with the whole page layout. Shrinking the selects to a more reasonable width fixes this and makes the site more usable. http://otaqui.com/code/bbc-fisheye/bbc-fisheye.user.js // ==UserScript== // @name BBC...  <a href="http://otaqui.com/blog/646/bbc-fisheye-greasemonkey-script/" class="more-link" title="Read BBC Fisheye Greasemonkey Script">Read more &#187;</a>]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.greasespot.net/">Greasemonkey</a> script to reformat &#8220;Author&#8221; select elements on the BBC&#8217;s Fisheye repository browser, which are ridiculously long (because they contain a considerable chunk of certificate data) which messes with the whole page layout.  Shrinking the selects to a more reasonable width fixes this and makes the site more usable.</p>
<p><a href="http://otaqui.com/code/bbc-fisheye/bbc-fisheye.user.js">http://otaqui.com/code/bbc-fisheye/bbc-fisheye.user.js</a></p>
<pre class="brush: javascript">
// ==UserScript==
// @name           BBC FishEye
// @namespace      http://otaqui.com/code/bbc-fisheye
// @description    Make BBC&#039;s Fisheye look more like it should
// @include        https://fisheye.dev.bbc.co.uk/*
// ==/UserScript==
var elems = document.evaluate(
    &#039;//select[@name=&quot;wbauthor&quot;]&#039;,
    document,
    null,
    XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,
    null
);
var i=0;
var sel;
while ( sel = elems.snapshotItem(i++) ) sel.style.width = &#039;200px&#039;;
</pre>
]]></content:encoded>
			<wfw:commentRss>http://otaqui.com/blog/646/bbc-fisheye-greasemonkey-script/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Fix The &#8220;For Attribute Resets Focus on Select Tag&#8221; Bug In Internet Explorer using Prototype</title>
		<link>http://otaqui.com/blog/435/fix-the-for-attribute-resets-focus-on-select-tag-bug-in-internet-explorer-using-prototype/</link>
		<comments>http://otaqui.com/blog/435/fix-the-for-attribute-resets-focus-on-select-tag-bug-in-internet-explorer-using-prototype/#comments</comments>
		<pubDate>Tue, 17 Feb 2009 10:20:36 +0000</pubDate>
		<dc:creator>pete</dc:creator>
				<category><![CDATA[Professional]]></category>
		<category><![CDATA[internet-explorer]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://otaqui.com/blog/?p=435</guid>
		<description><![CDATA[Browser sniffing is bad, or so the logic goes. There are occasions though where it makes perfect sense &#8211; for example where you are fixing a known bug in a specific version of a browser. A good example is the bug in IE 6 that resets the selected index of a Select tag that has...  <a href="http://otaqui.com/blog/435/fix-the-for-attribute-resets-focus-on-select-tag-bug-in-internet-explorer-using-prototype/" class="more-link" title="Read Fix The &#8220;For Attribute Resets Focus on Select Tag&#8221; Bug In Internet Explorer using Prototype">Read more &#187;</a>]]></description>
			<content:encoded><![CDATA[<p>Browser sniffing is <em>bad</em>, or so the logic goes.</p>
<p>There are occasions though where it makes perfect sense &#8211; for example where you are fixing a known bug in a specific version of a browser.  A good example is the bug in IE 6 that resets the selected index of a Select tag that has a label and the for attribute.  This bug doesn&#8217;t affect IE 7 or 8, or any other browser, but does make for a bad user experience if you are doing the right thing and including labels for your select tags.</p>
<p>Microsoft has <a href="http://support.microsoft.com/kb/314279">published some javascript to fix this</a> and I adapted their code to work with with the <a href="http://prototypejs.org">Prototype Javascript Library</a>.</p>
<p>This fix will look for all select tags on the page (you could adapt it to only look for those with the &#8220;for&#8221; attribute but I have a sneaking suspicion that if anything that would in fact be a bit slower) and observe the onfocusin and onfocus events as suggested in the knowledge base article.</p>
<pre class="brush: javascript">
// Select with &#039;for&#039; attribute fix for IE
Event.observe(window,&#039;load&#039;,function() {
	if ( !Prototype.Browser.IE || !(parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf(&quot;MSIE&quot;)+5))==6) ) return;
	$$(&#039;select&#039;).each(function(eSelect) {
		eSelect.observe(&#039;focusin&#039;,function(e) {
			try {
				var eSrc = window.event.srcElement;
				if ( eSrc ) eSrc.tmpIndex = eSrc.selectedIndex;
			} catch(e) {}
		});
		eSelect.observe(&#039;focus&#039;,function(e) {
			try {
				var eSrc = window.event.srcElement;
				if ( eSrc ) eSrc.selectedIndex = eSrc.tmpIndex;
			} catch(e) {}
		})
	});
});
</pre>
]]></content:encoded>
			<wfw:commentRss>http://otaqui.com/blog/435/fix-the-for-attribute-resets-focus-on-select-tag-bug-in-internet-explorer-using-prototype/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

