<?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>Solutoire.com &#187; Javascript</title>
	<atom:link href="http://solutoire.com/category/javascript/feed/" rel="self" type="application/rss+xml" />
	<link>http://solutoire.com</link>
	<description>Publicing platform</description>
	<lastBuildDate>Thu, 26 Feb 2009 17:07:57 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.6</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Sending Javascript Functions Over JSON</title>
		<link>http://solutoire.com/2008/06/12/sending-javascript-functions-over-json/</link>
		<comments>http://solutoire.com/2008/06/12/sending-javascript-functions-over-json/#comments</comments>
		<pubDate>Thu, 12 Jun 2008 11:55:58 +0000</pubDate>
		<dc:creator>Bas Wenneker</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Flotr]]></category>
		<category><![CDATA[json]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://solutoire.com/?p=172</guid>
		<description><![CDATA[
In this post I&#8217;ll present a way to send javascript functions over JSON from a php server (but it should work on other platforms too). Since PHP version 5.20 PHP includes the functions json_encode() and json_decode(). These functions encode values into JSON formatting and decode JSON formatted strings into associative arrays. The json_encode() function is [...]]]></description>
			<content:encoded><![CDATA[<p>
In this post I&#8217;ll present a way to send javascript functions over JSON from a php server (but it should work on other platforms too). Since PHP version 5.20 PHP includes the functions <code><a href="http://us.php.net/json_encode" title="PHP.net: json_encode()">json_encode()</a></code> and <code><a href="http://us.php.net/json_decode" title="PHP.net: json_decode()">json_decode()</a></code>. These functions encode values into JSON formatting and decode JSON formatted strings into <a href="http://en.wikipedia.org/wiki/Associative_array" title="Wikipedia: Associative array">associative arrays</a>. The <code>json_encode()</code> function is not able to encode a value into a (javascript) function. This is a common issue when configuring graphs from <a href="http://www.solutoire.com/flotr" title="Flotr Javascript Plotting Library">Flotr</a> (my Javascript plotting library) with JSON data. Here are my findings.
</p>
<h2>The Problem: Server-side</h2>
<p>
To get a better feeling for the problem, I&#8217;ll show you what happens when we pass an array to json_encode:
</p>
<pre class="php"><code>// Our sample array
$foo = array(
  'number'  => 1,
  'float'   => 1.5,
  'array'   => array(1,2),
  'string'  => 'bar',
  'function'=> 'function(){return "foo bar";}'
);

// Now encode the array to JSON format
$json = json_encode($foo);

// Send to to the client
echo $json;
...
// This sends the following string to the client:
{
  "number":1,
  "float":1.5,
  "array":[1,2],
  "string":"bar",
  "function":"function(){return \"foo bar\";}"
}</code></pre>
<p>
Because PHP reports some errors when we don&#8217;t enclose the &#8216;function&#8217; with quotation marks, it not possible to omit those. So basically, it&#8217;s not possible to use <code>json_encode()</code> to create a JSON formatted string with functions.
</p>
<h2>The solution</h2>
<p>
My solution is very simple:
</p>
<ul>
<li>Loop over the associative array that is about to be encoded</li>
<li>Look for values that start with a function definition (like &#8216;function(&#8217;)</li>
<li>Remember the value and replace it with a unique key (within the assoc array)</li>
<li>Encode the changed assoc array to JSON using <code>json_encode()</code></li>
<li>Replace the unique keys enclosed in quotation marks with their original values</li>
<li>Echo the json string</li>
</ul>
<p>In PHP:</p>
<pre class="php"><code>// Our sample array
$foo = array(
  'number'  => 1,
  'float'   => 1.5,
  'array'   => array(1,2),
  'string'  => 'bar',
  'function'=> 'function(){return "foo bar";}'
);

$value_arr = array();
$replace_keys = array();
foreach($foo as $key => &#038;$value){
  // Look for values starting with 'function('
  if(strpos($value, 'function(')===0){
    // Store function string.
    $value_arr[] = $value;
    // Replace function string in $foo with a 'unique' special key.
    $value = '%' . $key . '%';
    // Later on, we'll look for the value, and replace it.
    $replace_keys[] = '"' . $value . '"';
  }
}

// Now encode the array to json format
$json = json_encode($foo);

// $json looks like:
{
  "number":1,
  "float":1.5,
  "array":[1,2],
  "string":"bar",
  "function":"%function%"
}

// Replace the special keys with the original string.
$json = str_replace($replace_keys, $value_arr, $json);

// Send to to the client
echo $json;

// This echoes the following string:
{
  "number":1,
  "float":1.5,
  "array":[1,2],
  "string":"bar",
  "function":function(){return "foo bar";}
}
</code></pre>
<p>
Now the &#8216;function&#8217; key is not a String anymore, but it&#8217;s a function. So our problem is solved. When using <a href="http://www.prototypejs.org/" title="Prototype Javascript Library">Prototype</a>, it will look something like this:
</p>
<pre><code>new Ajax.Request('json_server.php', {
  method:'get',
  onSuccess: function(transport){
     var json = transport.responseText.evalJSON();
     alert(json.function()); // => alerts 'foo bar'
   }
});</code></pre>
<p>
There might be dozens of solutions to the problem stated above, but I couldn&#8217;t find &#8216;em on the net. If you know a better technique, please share it!</p>
]]></content:encoded>
			<wfw:commentRss>http://solutoire.com/2008/06/12/sending-javascript-functions-over-json/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>GChart 0.2 alpha released</title>
		<link>http://solutoire.com/2007/12/11/gchart-02-alpha-released/</link>
		<comments>http://solutoire.com/2007/12/11/gchart-02-alpha-released/#comments</comments>
		<pubDate>Tue, 11 Dec 2007 10:53:49 +0000</pubDate>
		<dc:creator>Bas Wenneker</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[GChart]]></category>
		<category><![CDATA[google-chart-api]]></category>

		<guid isPermaLink="false">http://solutoire.com/2007/12/11/gchart-02-alpha-released/</guid>
		<description><![CDATA[
Today I released GChart 0.2 alpha.
GChart is a small piece of javascript (packed 2.4kb) that enables using the Google Chart API in an easy way. GChart translates passed options to a url that can be used to request a chart from the Google Chart API. Also it provides several ways to insert, apply or return [...]]]></description>
			<content:encoded><![CDATA[<p>
Today I released GChart 0.2 alpha.</p>
<blockquote><p>GChart is a small piece of javascript (packed 2.4kb) that enables using the Google Chart API in an easy way. GChart translates passed options to a url that can be used to request a chart from the Google Chart API. Also it provides several ways to insert, apply or return the chart based on the passed options.</p></blockquote>
<p>It implements almost all parameters the Google Chart API accepts. You can read more about it on the <a href="http://www.solutoire.com/gchart/" title="GChart Project Page">GChart Project Page</a>. For a quick download, go <a href="http://www.solutoire.com/download/gchart/gchart-0.2alpha.zip" title="Download GChart 0.2 alpha">here</a>, and if you just want to see the GChart source, go <a href="http://www.solutoire.com/download/gchart/gchart-0.2alpha_uncompressed.js" title="GChart 0.2 alpha source">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://solutoire.com/2007/12/11/gchart-02-alpha-released/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Google Chart API JS Wrapper: GChart</title>
		<link>http://solutoire.com/2007/12/07/google-chart-api-js-wrapper-gchart/</link>
		<comments>http://solutoire.com/2007/12/07/google-chart-api-js-wrapper-gchart/#comments</comments>
		<pubDate>Thu, 06 Dec 2007 23:47:36 +0000</pubDate>
		<dc:creator>Bas Wenneker</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[GChart]]></category>
		<category><![CDATA[google-chart-api]]></category>

		<guid isPermaLink="false">http://solutoire.com/2007/12/07/google-chart-api-js-wrapper-gchart/</guid>
		<description><![CDATA[
As soon as I read about the Google Chart API I started writing a javascript wrapper for it (I called it GChart). It&#8217;s not finished yet, but it has most functionality. The simple, text and extended encoding types are supported, as wel as datasets, size, legends, titles and different types of charts. GChart 0.1 alpha [...]]]></description>
			<content:encoded><![CDATA[<p>
As soon as I read about the <a href="http://code.google.com/apis/chart/" title="Google Chart API Project Page">Google Chart API</a> I started writing a javascript wrapper for it (I called it GChart). It&#8217;s not finished yet, but it has most functionality. The simple, text and extended encoding types are supported, as wel as datasets, size, legends, titles and different types of charts. <a href="http://www.solutoire.com/download/gchart.js" title="Download GChart.js" onclick="javascript:urchinTracker('DL:GChart.js');">GChart 0.1 alpha</a> is now available for download.
</p>
<h2>GChart</h2>
<p>To use GChart, just include <a href="http://www.solutoire.com/download/gchart.js" title="Download GChart.js" onclick="javascript:urchinTracker('DL:GChart.js');">gchart.js</a> in the header of your page, and when the window&#8217;s finished loading, do something like this:</p>
<pre><code class="javascript">Chart.render({
	renderTo: 'div-target', 	// Target element to append the image to.
	data: [[1,10,3],[14,20,213]], 	// Two datasets.
	encoding: 't',			// Use the text encoding.
	title: 'Foo',			// Set the title of the chart.
	type: 'lc'			// Specify the type.
	axistype: 'x,y'			// Specify the axis type.
	size: '300x200'			// Specify the size of the chart.
});
</code></pre>
<div class="img">
<img src="http://chart.apis.google.com/chart?chs=300x200&#038;chd=t:1,10,3|14,20,213&#038;cht=lc&#038;chtt=Foo&#038;chxt=x,y" alt="Google Chart API" /><br />
<i>Chart generated with the code above.</i>
</div>
<p>The type, axistype and size have default values, but I added them for illustration. This javascript appends a basic chart to &#8216;div-target&#8217;. The options you can pass to <code>GChart.render()</code> are:</p>
<pre><code class="javascript">/**
 * @type {String/Element} The id of the node or a DOM node that will be the container to render the chart into.
 */
renderTo: false,
/**
 * @type {String/Element} The id of the node or a DOM node corresponding to an IMG that is already present.
 */
applyTo: false,
/**
 * @type {String} Specifies the size of the chart like <width in pixels>x<height in pixels> (defaults to 300x200).
 */
size: '300x200',
/**
 * @type {String} Specifies the type of the chart (defaults to 'lc').
 */
type: 'lc',
/**
 * @type {String} Specifies the chart encoding, can be 'simple' or 's', 'text' or 't' and 'extended' or 'e' (defaults to 's').
 */
encoding: 's',
/**
 * @type {String/Array} Dataset(s) for the chart, can be a multidimensional array or a encoded string (defaults to []).
 */
data: [],
/**
 * @type {Integer} Specifies the max value of a dataset, read <http://code.google.com/apis/chart/#encoding_data> maxValue (defaults to false).
 */
max: false,
/**
 * @type {String} Image alt attribute (defaults to '').
 */
alt: '',
/**
 * @type {String} Chart title (defaults to null).
 */
title: null,
/**
 * @type {String/Array} Legend, can be an array or a formatted string (defaults to null).
 */
legend: null,
/**
 * @todo implement!
 * @type {String/Array} Labels for the dataset(s), can be an array or a formatted string (defaults to []).
 */
labels: [],
/**
 * @type {String} Axis type.
 */
axistype: 'x,y'
</code></pre>
<p>
As you can see I implemented just a few of the API supported arguments, but I expect to have implemented all arguments this weekend.
</p>
<p>
To get started, you should first get familiar with the <a href="http://code.google.com/apis/chart/" title="Google Chart API Docs">Chart API</a>. It&#8217;s necessary you understand the encoding types. GChart accepts all of them, but also it accepts an array of datasets and encodes it for the encoding type you specify.</p>
]]></content:encoded>
			<wfw:commentRss>http://solutoire.com/2007/12/07/google-chart-api-js-wrapper-gchart/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Javascript left-hand assignment</title>
		<link>http://solutoire.com/2007/10/29/javascript-left-hand-assignment/</link>
		<comments>http://solutoire.com/2007/10/29/javascript-left-hand-assignment/#comments</comments>
		<pubDate>Mon, 29 Oct 2007 16:13:34 +0000</pubDate>
		<dc:creator>Bas Wenneker</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[list]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://solutoire.com/2007/10/29/javascript-left-hand-assignment/</guid>
		<description><![CDATA[
Wouldn&#8217;t it be great to do something like this in javascript:

function test(){
	return ['first!', 'second!'];
}

[first, second] = test();

alert(first); // should say 'first!'
alert(second); // should say 'second!'


I was inspired by the PHP list function. Funny enough it worked in Firefox and Opera, but Safari and IE failed this simple test. A bit disappointed I came up with [...]]]></description>
			<content:encoded><![CDATA[<p>
Wouldn&#8217;t it be great to do something like this in javascript:
</p>
<pre><code class="javascript">function test(){
	return ['first!', 'second!'];
}

[first, second] = test();

alert(first); // should say 'first!'
alert(second); // should say 'second!'
</code></pre>
<p>
I was inspired by the <a href="http://nl3.php.net/list">PHP list function</a>. Funny enough it worked in Firefox and Opera, but Safari and IE failed this simple test. A bit disappointed I came up with a <code>list()</code> implementation in javascript:
</p>
<pre><code class="javascript">// My list javascript implementation.
function list(variables, values, scope){
	for(var i = 0; i < variables.length &#038;&#038; i < values.length; i++){
		(scope || this)[variables[i]] = values[i];
	}
}

// Example usage:
list(['first','second'], test());
alert(first); // says 'first!'
alert(second); // says 'second!'

// Example explaining the scope argument.
var obj = {};
list(['first','second'], test(), obj);
alert('obj.first:'+obj.first); // says 'obj.first:first!'
alert('obj.second:'+obj.second); // says 'obj.second:second!'
</code></pre>
<p>
The <code>list</code> function takes three arguments. The first argument is an array of variable names and the second one is an array of values. The values are mapped on the variable names. The variables are available in the passed scope (the third argument). The default scope is the 'this' scope. When you're not familiar with the scope thingy, go read <a href="http://novemberborn.net/javascript/scopes-and-closures-funk">'Getting Funky With Scopes and Closures'</a> written by Mark Wubben.</p>
]]></content:encoded>
			<wfw:commentRss>http://solutoire.com/2007/10/29/javascript-left-hand-assignment/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Three handy javascript techniques</title>
		<link>http://solutoire.com/2007/08/21/three-handy-javascript-techniques/</link>
		<comments>http://solutoire.com/2007/08/21/three-handy-javascript-techniques/#comments</comments>
		<pubDate>Tue, 21 Aug 2007 09:17:03 +0000</pubDate>
		<dc:creator>Bas Wenneker</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[arguments]]></category>
		<category><![CDATA[efficiency]]></category>

		<guid isPermaLink="false">http://solutoire.com/2007/08/21/three-handy-javascript-techniques/</guid>
		<description><![CDATA[
In this post I&#8217;ll share three might-come-in-handy javascript techniques I often use. These techniques are: using the javascript &#8216;with&#8217; keyword, using the &#8216;String.indexOf&#8217; function to shorten if conditions, and using the &#8216;arguments&#8217; array to get a better understanding of how (undocumented) functions work.

The javascript &#8216;with&#8217; keyword

The javascript with keyword is a handy function when you&#8217;re [...]]]></description>
			<content:encoded><![CDATA[<p>
In this post I&#8217;ll share three might-come-in-handy javascript techniques I often use. These techniques are: using the javascript &#8216;with&#8217; keyword, using the &#8216;String.indexOf&#8217; function to shorten if conditions, and using the &#8216;arguments&#8217; array to get a better understanding of how (undocumented) functions work.
</p>
<h2>The javascript &#8216;with&#8217; keyword</h2>
<p>
The javascript <code>with</code> keyword is a handy function when you&#8217;re dealing with long namespaces like <code>objname.attributename.element.style.display</code>. Here&#8217;s an example:
</p>
<pre><code class="javascript">// Original code.
object.attr.element.style.display = 'block';
object.attr.element.style.padding = '10px';
object.attr.element.style.fontSize = '1.4em';

// Code using 'with'.
with(object.attr.element.style){
	display = 'block';
	padding = '10px';
	fontSize = '1.4em'
}

// Another example.
var foo = object.attr.arrayObj[0].value;
var bar = object.attr.arrayObj[1].value;
var baz = object.attr.arrayObj[2].options[object.attr.arrayObj[2].selectedIndex];

// Example nested 'with'
with(object.attr){
	var foo = arrayObj[0].value;
	var bar = arrayObj[1].value;
	with(arrayObj[2]){
		var baz = options[selectedIndex];
	}
}
</code></pre>
<p>
Note that code without <code>with</code> is slightly faster because <code>with</code> forces the specified object to be searched first for all unqualified name lookups. The with keyword can help reducing the file size of your javascript. Read more about it on <a href="http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Statements:with" title="Mozilla Development Center about javascript with keyword">Mozilla Development Center</a>.
</p>
<h2>Replacing if conditions with &#8216;String.indexOf&#8217;</h2>
<p>
If you have an <code>if</code> condition and you&#8217;re comparing a variable with some string, use <code>String.indexOf</code> to shorten the condition:
</p>
<pre><code class="javascript">var tagname = document.getElementById('someElement').tagName.toLowerCase();

if(tagname == 'div' || tagname == 'input' ||
	tagname == 'p' || tagname == 'span'	||
	tagname == 'blockquote'){
	// do some action
}

if('div|input|p|span|blockquote'.indexOf(el.tagName.toLowerCase()) != -1){
	// do some action
}
</code></pre>
<p>
This technique also reduces the file size, but the computation if the index might take a little longer. When you&#8217;re not using this in loops that loop more than 100 times, I don&#8217;t think you&#8217;ll notice a delay.
</p>
<h2>Using the &#8216;arguments&#8217; variable</h2>
<p>
I find myself using the <code>arguments</code> array quite a lot when debugging. It&#8217;s an easy way to understand how a function&#8217;s called, and which arguments are passed to it. In some older browsers there are two handy properties in the <code>arguments</code> variable: <code>arguments.caller</code> and <code>arguments.callee</code>. Modern browsers deprecated those two, but kept the <code>arguments.length</code> property. Here&#8217;s an example:</p>
<pre><code class="javascript">// You want to know which arguments are passed to someFunc().
function someFunc(){
	for(var i = 0; i < arguments.length; i++){
		alert(arguments[i]);
	}
}
</code></pre>
<p>
I think most people already knew this one. But when you're learning a new javascript lib with a lack of documentation, or trying out code someone else wrote (without proper documentation), this technique let's you understand functions much quicker/better. Read more about <code>arguments</code> on the <a href="http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Functions:arguments" title="Mozilla Development Center on arguments">Mozilla Development Center</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://solutoire.com/2007/08/21/three-handy-javascript-techniques/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Detecting Gears and Dojo Offline</title>
		<link>http://solutoire.com/2007/06/21/detecting-gears-and-dojo-offline/</link>
		<comments>http://solutoire.com/2007/06/21/detecting-gears-and-dojo-offline/#comments</comments>
		<pubDate>Thu, 21 Jun 2007 07:06:53 +0000</pubDate>
		<dc:creator>Bas Wenneker</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[dojo]]></category>
		<category><![CDATA[dojo-offline-toolkit]]></category>
		<category><![CDATA[google-gears]]></category>
		<category><![CDATA[local-storage]]></category>

		<guid isPermaLink="false">http://solutoire.com/2007/06/21/detecting-gears-and-dojo-offline/</guid>
		<description><![CDATA[
I was wondering if I could sniff whether or not a visitor has the Dojo Offline Toolkit or Google Gears installed. So I took a dive in their code and I came up with the following.

// Detect Google Gears.
try{
	window.gears = !!(typeof GearsFactory != 'undefined' &#124;&#124; navigator.mimeTypes['application/x-googlegears'] &#124;&#124; new ActiveXObject('Gears.Factory'));
}catch(e){}

// Detect Dojo Offline.
var head = document.getElementsByTagName('head')[0];
var [...]]]></description>
			<content:encoded><![CDATA[<p>
I was wondering if I could sniff whether or not a visitor has the <a href="http://dojotoolkit.org/offline" title="Dojo Offline Toolkit">Dojo Offline Toolkit</a> or <a href="http://code.google.com/apis/gears/" title="Google Gears developers site">Google Gears</a> installed. So I took a dive in their code and I came up with the following.
</p>
<pre><code class="javascript">// Detect Google Gears.
try{
	window.gears = !!(typeof GearsFactory != 'undefined' || navigator.mimeTypes['application/x-googlegears'] || new ActiveXObject('Gears.Factory'));
}catch(e){}

// Detect Dojo Offline.
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.setAttribute('src', 'http://localhost:8123/polipo/offline');
window.offlineCacheCallback = function(name, results){
	head = script = null;
	window.djoffline = true;
};
head.appendChild(script);

// Use a timeout because IE isn't finished
// with dojo on the window.onload event.
setTimeout(function(){
	alert('gears: ' + window.gears);
	alert('dojo offline: ' + window.djoffline);
},1000);
</code></pre>
<p>
To see this working, go visit the <a href="http://www.solutoire.com/experiments/gd_sniff.html">example page</a>. To detect Google Gears is quite obvious. Just check if some variables exist. To detect a Dojo Offline installation, we to insert a script tag in the html head. The script tags&#8217; src attribute points to some localhost service called <a href="http://www.pps.jussieu.fr/~jch/software/polipo/" title="Polipo, a caching web proxy">Polipo</a>, a caching web proxy Dojo Offline is built on. When the service exists, it&#8217;ll call the <code>window.offlineCacheCallback</code> function. So when that function is called, we know Dojo Offline is installed and running.
</p>
<h2>Other engines?</h2>
<p>
I also tried to sniff <a href="http://labs.adobe.com/technologies/air/">Adobe Air</a>, the former Adobe Appollo, but I couldn&#8217;t find a way to do this. I don&#8217;t think it&#8217;s possible to do this through javascript (only through flash/actionscript). Another client side storage provider is <a href="http://silverlight.net/">Microsoft Silverlight</a>. I didn&#8217;t do any research on this one, because I couldn&#8217;t get any examples running.</p>
]]></content:encoded>
			<wfw:commentRss>http://solutoire.com/2007/06/21/detecting-gears-and-dojo-offline/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Sorting javascript arrays</title>
		<link>http://solutoire.com/2007/05/02/sorting-javascript-arrays/</link>
		<comments>http://solutoire.com/2007/05/02/sorting-javascript-arrays/#comments</comments>
		<pubDate>Wed, 02 May 2007 19:07:50 +0000</pubDate>
		<dc:creator>Bas Wenneker</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[array.sort]]></category>
		<category><![CDATA[arrays]]></category>
		<category><![CDATA[sorting]]></category>

		<guid isPermaLink="false">http://solutoire.com/2007/05/02/sorting-javascript-arrays/</guid>
		<description><![CDATA[
Well, it&#8217;s been a while since my last post. I couldn&#8217;t find any interesting subjects to write about. Anyway, today I&#8217;ll write about sorting arrays. I&#8217;ll start with sorting arrays numerically and alphabetically, to introduce you some basic techniques. After that I&#8217;ll show you how to sort a multidimensional array.

Array.sort()

You can use Array.sort() for basic [...]]]></description>
			<content:encoded><![CDATA[<p>
Well, it&#8217;s been a while since my last post. I couldn&#8217;t find any interesting subjects to write about. Anyway, today I&#8217;ll write about sorting arrays. I&#8217;ll start with sorting arrays numerically and alphabetically, to introduce you some basic techniques. After that I&#8217;ll show you how to sort a multidimensional array.
</p>
<h2>Array.sort()</h2>
<p>
You can use Array.sort() for basic numerical and alphabetical sorting. Here are some examples:
</p>
<pre><code class="javascript">//sorting integers
[1,3,2,5,4].sort(); // => 1,2,3,4,5
//sorting floats
[1.2,1.1,1.5,2.6,0.21].sort(); // => 0.21, 1.1, 1.2, 1.5, 2.6
//sorting both integers and floats
[1.0,1,2,2.0,1.5,2.5].sort(); // => 1, 1, 1.5, 2, 2, 2.5

//sorting chars
['a','c','e','b','d'].sort(); // => a,b,c,d,e
//sorting strings
['aa','cz','bd','cc','bcc','bc'].sort(); // => aa,bc,bcc,bd,cc,cz
//sorting both strings and chars
['aa','az','b','cc','bc'].sort(); //=> aa,az,b,bc,cc

//sorting integers and strings
['a',1,'c',3,'e',2,'b','d'].sort(); // => 1,2,3,a,b,c,d,e
</code></pre>
<h2>Array.sort(callbackFunc)</h2>
<p>
You can also define your own sorting function. This callback function must have two input arguments, and always returns -1 (all integers < 0), 0 or 1(all integers > 0).
</p>
<ul>
<li>if callbackFunc(<em>a</em>,<em>b</em>) is less than 0, place <em>a</em> before <em>b</em>.</li>
<li>if callbackFunc(<em>a</em>,<em>b</em>) returns 0, leave <em>a</em> and <em>b</em> unchanged in respect to eachother.</li>
<li>if callbackFunc(<em>a</em>,<em>b</em>) is greater than 0, place <em>a</em> after <em>b</em>.</li>
</ul>
<p>
A basic example for sorting an array of integers using a callback function:
</p>
<pre><code class="javascript">function callbackFunc(a, b){
	return a - b;
}

[1,3,2,5,4].sort(callbackFunc); // => 1,2,3,4,5</code></pre>
<p>The callback function really come in handy to sort arrays of objects. Let&#8217;s say we have an array of object with three properties: &#8216;firstname&#8217;, &#8216;lastname&#8217; and &#8216;age&#8217;. Let&#8217;s say we want to sort the object on the lastname and on the firstname. This is a way we could sort those objects:</p>
<pre><code class="javascript">var objectArray = [
	{firstname: 'Marie', 	lastname: 'Doe', 	age: 28},
	{firstname: 'Will', 	lastname: 'Brown', 	age: 28},
	{firstname: 'James', 	lastname: 'White', 	age: 28},
	{firstname: 'John', 	lastname: 'Doe', 	age: 25},
	{firstname: 'Sarah', 	lastname: 'Doe', 	age: 25},
	{firstname: 'George', 	lastname: 'Williams', 	age: 25}
];

function callbackFunc(a,b){

	if(a.lastname == b.lastname){

		if(a.firstname == b.firstname){
			return 0;
		}

		return (a.firstname < b.firstname) ? -1 : 1;
	}

	return (a.lastname < b.lastname) ? -1 : 1;
}

objectArray.sort(callbackFunc);

/**
 * After sorting the objectArray will be like this:
 * [
 * 	{firstname: 'Will', 	lastname: 'Brown',	age: 28},
 * 	{firstname: 'John', 	lastname: 'Doe',	age: 25},
 * 	{firstname: 'Marie', 	lastname: 'Doe',	age: 28},
 * 	{firstname: 'Sarah', 	lastname: 'Doe',	age: 25},
 * 	{firstname: 'James', 	lastname: 'White',	age: 28},
 * 	{firstname: 'George', 	lastname: 'Williams',	age: 25}
 * ]
 */
</code></pre>
<p>
If you want to know more about sorting with Array.sort(), check out the <a href="http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Array:sort">Core JavaScript 1.5 Reference:Global Objects:Array:sort</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://solutoire.com/2007/05/02/sorting-javascript-arrays/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Troubleshooting Javascript</title>
		<link>http://solutoire.com/2007/04/06/troubleshooting-javascript/</link>
		<comments>http://solutoire.com/2007/04/06/troubleshooting-javascript/#comments</comments>
		<pubDate>Fri, 06 Apr 2007 19:51:04 +0000</pubDate>
		<dc:creator>Bas Wenneker</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[getting-help]]></category>

		<guid isPermaLink="false">http://solutoire.com/2007/04/06/troubleshooting-javascript/</guid>
		<description><![CDATA[
Lately I got a lot of questions (comments/emails) from people who have problems with getting their javascripts working. I really enjoy it when I can help other people with such things, but I&#8217;m a very busy man. So this article&#8217;ll be about getting help from javascript specialists. As you&#8217;ll see there are many places you [...]]]></description>
			<content:encoded><![CDATA[<p>
Lately I got a lot of questions (comments/emails) from people who have problems with getting their javascripts working. I really enjoy it when I can help other people with such things, but I&#8217;m a very busy man. So this article&#8217;ll be about getting help from javascript specialists. As you&#8217;ll see there are many places you can go when you&#8217;re stuck. Though, before asking questions, make sure you read every piece of documentation about your problem, google on it, maybe there&#8217;s someone with the same problem.
</p>
<h2>Some things you should know</h2>
<p>
Before telling you under which rocks you should look for javascript guru&#8217;s, I&#8217;ll give an example of how you should not ask for help. Panky wrote the <a href="http://solutoire.com/2006/11/29/mootools-the-ajax-class/#comment-1220">following comment</a> on an article I wrote:
</p>
<blockquote><p>
Hy! I used the full-full packed mootools (v1.0) and dosen’t work the code! What can I do? I don’t understand what’s the problem. :’(</p>
<p>Panky
</p></blockquote>
<p>
When I read this I needed about ten minutes to get back on my seat again because I was rolling on the floor laughing (read: rofl). If you&#8217;ve got a question/problem, you really have to be more specific. Always include the code that&#8217;s not working. Otherwise the javascript wizards can&#8217;t help! If it&#8217;s a lot of code and you don&#8217;t have your own website/ftp server, just drop the code at <a href="http://pastebin.com/">Pastebin</a>. Another important thing is to tell others which browser you&#8217;re testing with. Summarized:
</p>
<ul>
<li>Include the code that&#8217;s not working.</li>
<li>Post the name and version of the browser you&#8217;re testing with.</li>
</ul>
<h2>Google Groups</h2>
<p>
Don&#8217;t like newsgroups? Try <a href="http://groups.google.com/">Google Groups</a>! There are a lot of <a href="http://groups.google.com/groups/dir?lnk=srgmt&#038;q=javascript">javascript related groups</a>. Also you can find an awful lot of threads with questions, examples and solutions. There are even javascript groups in other languages than English. A good place to start is <a href="http://groups.google.com/group/comp.lang.javascript/topics?lnk=gschg">comp.lang.javascript</a>. All you have to do is subscribe to the group and you can start asking questions. Do you have a question about using a javascript framework? Just look around for framework specific groups like the ones for <a href="http://groups.google.com/group/jquery-en/topics">jQuery</a>, <a href="http://groups.google.com/group/Prototypejs?lnk=srg">Prototype</a> or the <a href="http://groups.google.com/group/Dojo-Toolkit?lnk=gschg">Dojo toolkit</a>.
</p>
<h2>Forums</h2>
<p>
Almost every framework has it&#8217;s own forum, so when you&#8217;re stuck with some framework specific code then you should definitely look around for the developers forums. Just like Google Groups there are lots of solved problems, maybe even that are the same like yours. To get you started, here&#8217;s the forum for <a href="http://forum.mootools.net/">Mootools</a>.
</p>
<h2>IRC and mailinglists</h2>
<p>
Well, I&#8217;m not using IRC or mailing lists, but I heard there are lots of javascript masterminds hiding from the crowd.
</p>
<p style="margin-top:10px">So, now you know where to look for javascript Buddha&#8217;s, also don&#8217;t hesitate to ask me!</p>
]]></content:encoded>
			<wfw:commentRss>http://solutoire.com/2007/04/06/troubleshooting-javascript/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>HistMan v0.2: Port to Prototype</title>
		<link>http://solutoire.com/2007/03/20/histman-v02-released-for-mootools-and-prototype/</link>
		<comments>http://solutoire.com/2007/03/20/histman-v02-released-for-mootools-and-prototype/#comments</comments>
		<pubDate>Tue, 20 Mar 2007 21:16:15 +0000</pubDate>
		<dc:creator>Bas Wenneker</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[histman]]></category>
		<category><![CDATA[history-management]]></category>
		<category><![CDATA[Mootools]]></category>
		<category><![CDATA[Prototype]]></category>

		<guid isPermaLink="false">http://solutoire.com/2007/03/20/histman-v02-released-for-mootools-and-prototype/</guid>
		<description><![CDATA[
Just a day after the launch of HistMan I&#8217;m releasing v0.2. I&#8217;ve also ported this version to Prototype, so now Mootools and Prototype are supported.


Version 0.2 has different syntax than 0.1. It now looks in the dom automatically for elements with the &#8216;history&#8217; attribute set, so you don&#8217;t have to pass the elements to HistMan.start(). [...]]]></description>
			<content:encoded><![CDATA[<p>
Just a day after the launch of HistMan I&#8217;m releasing v0.2. I&#8217;ve also ported this version to Prototype, so now Mootools and Prototype are supported.
</p>
<p>
Version 0.2 has different syntax than 0.1. It now looks in the dom automatically for elements with the &#8216;history&#8217; attribute set, so you don&#8217;t have to pass the elements to <code>HistMan.start()</code>. Also, you can add elements programmatically to the HistMan register by using some javascript. Just take a look at the <a href="http://www.solutoire.com/histman/">project page</a> for more information and downloads.</p>
]]></content:encoded>
			<wfw:commentRss>http://solutoire.com/2007/03/20/histman-v02-released-for-mootools-and-prototype/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>HistMan: Javascript History Manager</title>
		<link>http://solutoire.com/2007/03/19/histman-javascript-history-manager/</link>
		<comments>http://solutoire.com/2007/03/19/histman-javascript-history-manager/#comments</comments>
		<pubDate>Mon, 19 Mar 2007 20:49:30 +0000</pubDate>
		<dc:creator>Bas Wenneker</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[bookmarking]]></category>
		<category><![CDATA[histman]]></category>
		<category><![CDATA[history-management]]></category>

		<guid isPermaLink="false">http://solutoire.com/2007/03/19/histman-javascript-history-manager/</guid>
		<description><![CDATA[
HistMan is a script that let’s you manage browser history (back/forward buttons) and bookmarking in Ajax applications using Mootools. My aim is to deliver a small and efficient framework that’s easily ported to frameworks other than Mootools. At the time of writing the supported browsers are FF2, IE6+ and Opera9. I haven’t tested with Safari [...]]]></description>
			<content:encoded><![CDATA[<p>
HistMan is a script that let’s you manage browser history (back/forward buttons) and bookmarking in Ajax applications using Mootools. My aim is to deliver a small and efficient framework that’s easily ported to frameworks other than Mootools. At the time of writing the supported browsers are FF2, IE6+ and Opera9. I haven’t tested with Safari yet. You can try it out at the <a href="http://solutoire.com/experiments/histman/histman_ex1.html">HistMan example page</a>, for more information and the download, go the the <a href="http://solutoire.com/histman/">HistMan project page</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://solutoire.com/2007/03/19/histman-javascript-history-manager/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>
