<?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"
	>

<channel>
	<title>Hacking at 0300</title>
	<atom:link href="http://youngisrael-stl.org/wordpress/feed/" rel="self" type="application/rss+xml" />
	<link>http://youngisrael-stl.org/wordpress</link>
	<description>Thoughts on web design and programming from a very occasional volunteer webmaster</description>
	<pubDate>Fri, 24 Oct 2008 05:30:44 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.6</generator>
	<language>en</language>
			<item>
		<title>Turning a table into a list in Excel</title>
		<link>http://youngisrael-stl.org/wordpress/2008/10/23/turning-a-table-into-a-list-in-excel/</link>
		<comments>http://youngisrael-stl.org/wordpress/2008/10/23/turning-a-table-into-a-list-in-excel/#comments</comments>
		<pubDate>Fri, 24 Oct 2008 05:29:45 +0000</pubDate>
		<dc:creator>Danny</dc:creator>
		
		<category><![CDATA[Microsoft Office]]></category>

		<guid isPermaLink="false">http://youngisrael-stl.org/wordpress/?p=158</guid>
		<description><![CDATA[The yomim tovim are over, so I will hopefully have a chance to play with jQuery again. But on the programming side, one thing I had to do was turn a table of honors, something like this:


Rosh Hashana 1Rosh Hashana 2Yom Kippur
MaarivPerson 1Person 2Person 3
ShacharitPerson 4Person 5Person 6
MusafPerson 7Person 8Person 9


And turn it into this:

WhenWhatWho
Rosh [...]]]></description>
			<content:encoded><![CDATA[The yomim tovim are over, so I will hopefully have a chance to play with jQuery again. But on the programming side, one thing I had to do was turn a table of honors, something like this:
<table border="1">
<tbody>
<tr><td></td><td>Rosh Hashana 1</td><td>Rosh Hashana 2</td><td>Yom Kippur</td></tr>
<tr><td>Maariv</td><td>Person 1</td><td>Person 2</td><td>Person 3</td></tr>
<tr><td>Shacharit</td><td>Person 4</td><td>Person 5</td><td>Person 6</td></tr>
<tr><td>Musaf</td><td>Person 7</td><td>Person 8</td><td>Person 9</td></tr>
</tbody>
</table>
And turn it into this:
<table border="1">
<tr><td>When</td><td>What</td><td>Who</td></tr>
<tr><td>Rosh Hashana 1</td><td>Maariv</td><td>Person 1</td></tr>
<tr><td>Rosh Hashana 1</td><td>Shacharit</td><td>Person 4</td></tr>
<tr><td>Rosh Hashana 1</td><td>Musaf</td><td>Person 7</td></tr>
<tr><td>Rosh Hashana 2</td><td>Maariv</td><td>Person 2</td></tr>
<tr><td>Rosh Hashana 2</td><td>Shacharit</td><td>Person 5</td></tr>
<tr><td>Rosh Hashana 2</td><td>Musaf</td><td>Person 8</td></tr>
<tr><td>Yom Kippur</td><td>Maariv</td><td>Person 3</td></tr>
<tr><td>Yom Kippur</td><td>Shacharit</td><td>Person 6</td></tr>
<tr><td>Yom Kippur</td><td>Musaf</td><td>Person 9</td></tr>
<tbody>
</tbody>
</table>
<span id="more-158"></span>
I used code like this:
<pre><code class="language-vb">
Sub createlist()
    Dim source As Range
    Set source = Range("B2:D4")
    Dim dest As Range
    Set dest = Range("F1")
    dest.Range("A1:C1").Value = Array("When", "What", "Who")
    Dim target As Range
    Dim c As Range
    For Each c In source.Cells
        If Not IsEmpty(c.Value) Then
            If IsEmpty(dest.Range("A2").Value) Then
                Set target = dest.Range("A2")
            Else
                Set target = dest.End(xlDown).Range("A2")
            End If
            target.Range("C1").Formula = "=" &#038; c.Address
            target.Range("B1").Formula = "=" &#038; c.EntireRow.Range("A1").Address ' row header
            target.Range("A1").Formula = "=" &#038; c.EntireColumn.Range("A1").Address ' column header
        End If
    Next c
End Sub
</code></pre>

<p>The key tricks was getting column/row headers with <code class="language-vb">.EntireColumn/Row.Range("A1")</code>, and appending to the end of a list with
<code class="language-vb">.End(xlDown).Range("A2")</code>. Unfortunately, <code>End(xlDown)</code> is too clever; if the region contains only one item (like the column header only), it goes all the way to the end of the spreadsheet and the <code>.Range("A2")</code>, which should get the <em>next</em> line, throws an error. Hence the <code class="language-vb">If IsEmpty(dest.Range("A2").Value) Then</code>.</p>
<p>The <code class="language-vb">If Not IsEmpty(c.Value) Then</code> line allows for blank spots in the original table to be ignored. VBA doesn't have a <code>Continue</code> statement, just an equivalent for <code>break</code>, called <code class="language-vb">Exit For</code>.]]></content:encoded>
			<wfw:commentRss>http://youngisrael-stl.org/wordpress/2008/10/23/turning-a-table-into-a-list-in-excel/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Changes</title>
		<link>http://youngisrael-stl.org/wordpress/2008/10/23/changes/</link>
		<comments>http://youngisrael-stl.org/wordpress/2008/10/23/changes/#comments</comments>
		<pubDate>Fri, 24 Oct 2008 04:25:02 +0000</pubDate>
		<dc:creator>Danny</dc:creator>
		
		<category><![CDATA[Web Design]]></category>

		<guid isPermaLink="false">http://youngisrael-stl.org/wordpress/?p=155</guid>
		<description><![CDATA[Switched themes to Barthelme; very simple and elegant. Removed the Chili code highlighting line-numbering, which only worked intermittently, tended to get lost in the margins of the &#60;pre&#62; elements, and didn't add much.]]></description>
			<content:encoded><![CDATA[Switched themes to <a href="http://www.plaintxt.org/themes/barthelme/">Barthelme</a>; very simple and elegant. Removed the Chili code highlighting line-numbering, which only worked intermittently, tended to get lost in the margins of the &lt;pre&gt; elements, and didn't add much.]]></content:encoded>
			<wfw:commentRss>http://youngisrael-stl.org/wordpress/2008/10/23/changes/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Making $.metadata Extensible</title>
		<link>http://youngisrael-stl.org/wordpress/2008/08/29/making-metadata-extensible/</link>
		<comments>http://youngisrael-stl.org/wordpress/2008/08/29/making-metadata-extensible/#comments</comments>
		<pubDate>Fri, 29 Aug 2008 07:20:59 +0000</pubDate>
		<dc:creator>Danny</dc:creator>
		
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://youngisrael-stl.org/wordpress/?p=108</guid>
		<description><![CDATA[



	$(function(){
		$('.example').css({
			'float': 'left',
			border: '2px solid #0f0',
			padding: '5px',
			margin: '5px'
		});
		
		$('.examplebutton').click(function(){
			var opts = eval(/(\({.*}\))/.exec(this.value)[1]);
			alert(JSON.stringify($(this).prev('.example').metadata(opts)));
		}).after('');
	});

Metadata
I put the idea that the metadata plugin should be extensible 
out on the 
jquery discussion group, but it got no attention, so I'm documenting it here.

Metadata is information about a DOM element that isn't part of the actual text; e.g. you mention New York City [...]]]></description>
			<content:encoded><![CDATA[<script src="http://svn.danwebb.net/external/microformat/microformat.js"></script>
<script src="http://svn.danwebb.net/external/microformat/hcard.js"></script>
<script src="http://www.json.org/json2.js"></script>
<script>
	$(function(){
		$('.example').css({
			'float': 'left',
			border: '2px solid #0f0',
			padding: '5px',
			margin: '5px'
		});
		
		$('.examplebutton').click(function(){
			var opts = eval(/(\({.*}\))/.exec(this.value)[1]);
			alert(JSON.stringify($(this).prev('.example').metadata(opts)));
		}).after('<br style="clear: both"/>');
	});
</script>
<h4>Metadata</h4>
<p>I put the idea that the metadata plugin should be extensible 
out on <a href="http://groups.google.com/group/jquery-en/browse_thread/thread/5ca1030e55c4a561/c41dc8f214ad7c91">the 
jquery discussion group</a>, but it got no attention, so I'm documenting it here.</p>
<span id="more-108"></span>
<p>Metadata is information about a DOM element that isn't part of the actual text; e.g. you mention New York City and somehow associate the coordinates
[40.783, -73.967] with that. Scripts can use that information to add to the user experience; in this case, you could point the city out on a map.</p>
<p>There are two reasons to use metadata, for good or for evil:</p>
<ol>
	<li>For good: the metadata is semantic, related to the actual information present on the page and the metadata helps build the 
	<a href="http://en.wikipedia.org/wiki/Semantic_Web">semantic web</a>.</li>
	<li>For evil: as a way of mixing behavior and presentation in the semantic markup. In this sense, in-line style statements and 
	<code>class="draggable"</code> sorts of things
	are metadata.</li>
</ol>
<p>I'm obviously being tongue-in-cheek here; mixing presentation and markup isn't really evil. Having everything on one page is both faster to write, and,
for small projects, easier to understand.</p>
<h4>The metadata plugin</h4>
<p>The <a href="http://plugins.jquery.com/project/metadata">jquery metadata plugin</a> provides a way of getting metadata out of an element
and into a javascript object that you can use. <code class="language-javascript">obj = $('#foo').metadata()</code> analyzes the foo element
for metadata and returns it. For efficiency's sake, it stores that metadata in the jQuery cache under the key <code>'metadata'</code>,
so $('#foo').data('metadata') will get it back again, and in fact metadata first checks for that cache and only analyzes the element if it isn't found.
This means the analysis only happens once per element.
The key can be changed with the <code>single</code> option (calling it <code>single</code> is a historical accident, from previous versions of metadata that
used mulitple expandos on the element or combined them into one expando).</p>
<h4>Creating metadata</h4>
<p>The problem is that there is no standard for incorporating metadata into your markup. Lots of things have been proposed or used, like custom
attributes, pre-determined classes (the <a href="http://microformats.org/">microformats</a> approach) and 
<a href="http://www.w3.org/html/wg/html5/#custom">HTML5's data- attributes</a>. The metadata plugin allows for three methods: custom attributes, JSON in the className,
and the content of a specified child element (generally a &lt;script&gt; element with an unrecongnized type that will be ignored by the HTML parser). In the words of
the <a href="http://plugins.jquery.com/project/metadata">plugin documentation</a>, "This means that there is at least one option here that can appease you."</p>
<p>But that clearly isn't true. There are lots more ways to encode metadata, and there's no reason that the plugin should be limited to just three. Therefore, in the
spirit of jQuery, I made it freely extensible:</p>
<h4>The extensible metadata</h4>
<pre><code class="language-javascript demo">
$.extend({
	metadata : {
		defaults : {
			type: 'class',
			name: 'metadata',
			cre: /({.*})/,
			single: 'metadata'
		},
		setType: function( type, name ){
			this.defaults.type = type;
			this.defaults.name = name;
		},
		get: function( elem, opts ){
			var opts = $.extend({},this.defaults,opts);
			return $.data(elem, opts.single) || $.data(elem, opts.single, this[opts.type].call(elem,opts));
		},
		asJSON: function(s){
			if (!s) return {};
			if (/^[[{]/.test($.trim(s))) return eval("(" + s + ")");
			return s;
		}
	}
});

$.fn.metadata = function( opts ){
	return $.metadata.get( this[0], opts );
};
</code></pre>
<p>and all metadata "analyzing functions"--defined by the options.type string--take an options object and return the metadata object, with <code>this</code> bound to the element.</p>
<h4>The original three</h4>
<p>For example, the original metadata methods are:</p>
<pre><code class="language-javascript demo">
$.metadata["class"] = function (opts){
	var m = opts.cre.exec( this.className );
	if ( m ) return $.metadata.asJSON(m[1]);
	return {};
};

$.metadata.elem = function (opts){
	var e = this.getElementsByTagName(opts.name);
	if ( e.length ) return $.metadata.asJSON(e[0].innerHTML);
	return {};
};

$.metadata.attr = function (opts){
	var attr = this.getAttribute( opts.name );
	// allow for not including the braces, as in the original metadata plugin
	if ( attr ){
		if ( attr.indexOf( '{' ) &lt; 0 ) attr = "{" + attr + "}";
		return $.metadata.asJSON(attr);
	}
	return {};
};
</code></pre>

<h4>Example: type 'class'</h4>
<div>
<pre><code class="language-html demo">
&lt;div class=&quot;{ draggable : {axis: 'x', opacity: 0.5}} example&quot;&gt;I have data!&lt;/div&gt;
</code></pre>
<input type="button" class="examplebutton" value="Show Me the Data: metadata({type: 'class'})"/>
</div>

<h4>Example: type 'attr'</h4>
<div>
<pre><code class="language-html demo">
&lt;div coords=&quot;{lat: 40, long: -90}&quot; class=&quot;example&quot;&gt;I have data!&lt;/div&gt;
</code></pre>
<input type="button" class="examplebutton" value="Show Me the Data: metadata({type: 'attr', name: 'coords'})"/>
</div>

<h4>Example: type 'elem'</h4>
<div>
<pre><code class="language-html">
&lt;div class=&quot;example&quot;&gt;
&lt;script type=&quot;text/json&quot;&gt;{first: 1, second: 2}&lt;/script&gt;
I have data!
&lt;/div&gt;
</code></pre>
<div class="example" id="example3">
<script type="text/json">{first: 1, second: 2}</script>
I have data!
</div>
<input type="button" class="examplebutton" value="Show Me the Data: metadata({type: 'elem', name: 'script'})"/>
</div>

<h4>Example: metaobjects</h4>
<div>
<p>Andrea Ercolino's <a href="http://noteslog.com/metaobjects/">metaobjects</a> uses an <code>&lt;object&gt;</code> element to insert
metadata in a standards-compliant way, with the data in the <code>&lt;param&gt;</code> elements
<pre><code class="language-javascript demo">
$.metadata.object = function (opts){
	var ret = {};
	$('&gt; object.metaobject &gt; param', this).each(function(){
		ret[this.name] = $.metadata.asJSON(this.value);
	});
	return ret;
};
</code></pre>
<pre><code class="language-html demo">
&lt;div class=&quot;example&quot;&gt;I have data!
&lt;object class=&quot;metaobject&quot; style="display:none"&gt;
	&lt;param name=&quot;Full Name&quot; value=&quot;Danny W&quot;/&gt;
	&lt;param name=&quot;Age&quot; value=&quot;too large to count&quot; /&gt;
&lt;/object&gt;
&lt;/div&gt;
</code></pre>
<input type="button" class="examplebutton" value="Show Me the Data: metadata({type: 'object'})"/>
</div>

<h4>Example: Microformats</h4>
<div>
<p><a href="http://microformats.org/">Microformats</a> are a way of marking up metatdata that is actually present in the text so it becomes machine readable as well. <em>We</em> recognize that
"123 Sesame Street" is an address, but our programs aren't so smart unless we tell them: "<code>&lt;span class="street-address"&gt;</code>123 Sesame
Streetcode>&lt;/span&gt;</code>". <a href="http://www.danwebb.net">Dan Webb</a> wrote a clever microformat parsing program called 
<a href="http://www.danwebb.net/2007/2/9/sumo-a-generic-microformats-parser-for-javascript/">Sumo</a> that we'll use:
<pre><code class="language-javascript demo">
$.metadata.hcard = function(opts){
	var hcards = HCard.discover(this);
	return hcards.length ? hcards[0] : {};
};
</code></pre>
<p>Sumo uses a subset of <a href="http://www.prototypejs.org/">Prototype</a>; someday I may port it to jQuery.</p>
<pre><code class="language-html demo">
&lt;div class=&quot;example&quot;&gt;
  I have data from 
	&lt;span class=&quot;vcard&quot;&gt;
	  &lt;span class=&quot;fn&quot;&gt;Danny Wachsstock&lt;/span&gt;
		at &lt;span class=&quot;tel&quot;&gt;555-1212&lt;/span&gt;
	&lt;/span&gt;!
&lt;/div&gt;
</code></pre>
<input type="button" class="examplebutton" value="Show Me the Data: metadata({type: 'hcard'})"/>
</div>

<h4>HTML 5</h4>
<div>
<p>HTML5 allows for <a href="http://www.w3.org/html/wg/html5/#custom">custom attributes</a> on any element, as long as the name starts with
"data-". It's pretty controversial in the standardista community to allow this kind of freedom, but given that people are already doing it with
all sorts of attributes, it's a concession to the reality that the standards-setters don't know everything and can't predict everything.
<a href="http://ejohn.org">John Resig</a>
<a href="http://ejohn.org/blog/html-5-data-attributes/">likes it</a>, but it hasn't made it into the metadata plugin yet. Until now.</p>
<pre><code class="language-javascript demo">
$.metadata.data = function(opts){
	var ret = {};
	$.each (this.attributes, function(){
		var m = /data-(.*)/.exec(this.nodeName);
		if (m) ret[m[1]] = $.metadata.asJSON(this.nodeValue);
	});
	return ret;
};
</code></pre>
<pre><code class="language-html demo">
&lt;div data-lat=&quot;40&quot; data-long=&quot;-90&quot; class=&quot;example&quot;&gt;I have data!&lt;/div&gt;
</code></pre>
<input type="button" class="examplebutton" value="Show Me the Data: metadata({type: 'data'})"/>
</div>]]></content:encoded>
			<wfw:commentRss>http://youngisrael-stl.org/wordpress/2008/08/29/making-metadata-extensible/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Extending jQuery UI Widgets, The Final Chapter</title>
		<link>http://youngisrael-stl.org/wordpress/2008/08/22/extending-jquery-ui-widgets-the-final-chapter/</link>
		<comments>http://youngisrael-stl.org/wordpress/2008/08/22/extending-jquery-ui-widgets-the-final-chapter/#comments</comments>
		<pubDate>Fri, 22 Aug 2008 22:28:34 +0000</pubDate>
		<dc:creator>Danny</dc:creator>
		
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://youngisrael-stl.org/wordpress/?p=137</guid>
		<description><![CDATA[OK, this is the final update to the widget subclassing. Rather than creating a new method, $.widget.subclass, I created a single base widget
$.ui.widget that does nothing but includes the Aspect-Oriented-Programming code and a subclassing method. I put everything in the $.ui
namespace (since namespacing plugins doesn't work anyway, all plugin names need to be globally unique). [...]]]></description>
			<content:encoded><![CDATA[<p>OK, this is the final update to the widget subclassing. Rather than creating a new method, <code>$.widget.subclass</code>, I created a single base widget
<code>$.ui.widget</code> that does nothing but includes the Aspect-Oriented-Programming code and a subclassing method. I put everything in the <code>$.ui</code>
namespace (since namespacing plugins doesn't work anyway, all plugin names need to be globally unique). I removed the
<code>callSuper</code> method, since <code>this.callSuper('ui.widget', 'method', args)</code> is no better than just doing it straight, 
<code>$.ui.widget.prototype.method.apply(this, args)</code>.</p>
<p>Without further ado, here's the code (<a href="/inc/ui.subclass.js">download</a>):</p>
<span id="more-137"></span>
<pre><code class="language-javascript demo">
// create the master widget
$.widget("ui.widget",{
	// Aspect Oriented Programming tools from Justin Palmer's article
  yield: null,
  returnValues: { },
  before: function(method, f) {
    var original = this[method];
    this[method] = function() {
      f.apply(this, arguments);
      return original.apply(this, arguments);
    };
  },
  after: function(method, f) {
    var original = this[method];
    this[method] = function() {
      this.returnValues[method] = original.apply(this, arguments);
      return f.apply(this, arguments);
    }
  },
  around: function(method, f) {
    var original = this[method];
    this[method] = function() {
      this.yield = original;
      return f.apply(this, arguments);
    }
  }
});

function object(o){
	function F(){};
	F.prototype = o;
	return new F;
}

// create a widget subclass (always in the $.ui namespace)
$.ui.widget.subclass = function subclass(name) {
	$.widget('ui.'+name); // Slightly inefficient to create a widget only to discard its prototype, but it's not too bad
	var widget = $.ui[name]; // $.widget should return the object itself!
	widget.subclass = subclass;
	var superclass = this;
	
	widget.prototype = object(this.prototype);
	arguments[0] = widget.prototype; // add the the new methods to the prototype
	$.extend.apply(null, arguments); 
	widget.defaults = object(this.defaults);
	widget.getter = this.getter;
	
	// Subtle point: we want to call superclass init and destroy if they exist
	// (otherwise the user of this function would have to keep track of all that)
	if (widget.prototype.hasOwnProperty('init')){;
	  var init = widget.prototype.init;
		widget.prototype.init = function(){
			superclass.prototype.init.apply(this);
			init.apply(this);
		}
	};
	if (widget.prototype.hasOwnProperty('destroy')){
		var destroy = widget.prototype.destroy;
		widget.prototype.destroy = function(){
			destroy.apply(this);
			superclass.prototype.destroy.apply(this);
		}
	}
	return widget; // address my complaint above
};
</code></pre>
<script>
$(function(){
	$('.target').css({
		position: 'relative',
		background: 'green',
		padding: '5px',
                margin: '10px 0',
                border: '2px solid #0f0',
		height: '100px',
		width: '100px',
		color: 'white'
	});
	$('#home').click(function(){
		$('.target').animate({top: 0, left:0}, 'fast');
	});
});
</script>
<p>And here are the samples from the <a href="/wordpress/2008/08/13/extending-jquery-ui-widgets-revisited/">Extending Widgets tutorial</a>:</p>
<pre><code class="language-javascript demo">
//  Experiment 1
var Superbox = {
	init: function(){
		var self = this;
		this.element.click(function(){
			self.move();
		});
	},
	move: function(){
		this.element.css (this.newPoint());
	},
	newPoint: function(){
		return {top: this.distance(), left: this.distance()};
	},	
	distance: function(){
		return Math.round (Math.random()*this.getData('distance'));
	}
};
$.ui.widget.subclass ('superbox', Superbox);
$.ui.superbox.defaults = { distance: 200 };

$('#experiment1').superbox();

// Experiment 2
$.ui.superbox.subclass ('supererbox', {
	// overriding and new methods
	move: function(){
		this.element.animate(this.newPoint(), this.getData('speed'));
	},
	home: function(){
		this.element.animate({top:0, left:0}, this.getData('speed'));
	}
});
$.ui.supererbox.defaults.speed = 'normal';

$('#experiment2').supererbox();

// Experiment 3
$.ui.supererbox.subclass('superboxwithtext',  {
	move: function(){
		var count = this.getData('count') || 0;
		++count;
		this.setData('count', count);
		this.element.text('Move number '+count);
		$.ui.supererbox.prototype.move.call(this); // note that we could just as well use $.ui.superbox.move for the original, "jumpy" move
	}
});

$('#experiment3').superboxwithtext();

// Experiment 4
$.fn.pulse = function (opts){
	opts = $.extend ({}, $.fn.pulse.defaults, opts);
	for (i = 0; i &lt; opts.times; ++i){
		this.animate({opacity: 0.1}, opts.speed).animate({opacity: 1}, opts.speed);
	}
	return this;
};
$.fn.pulse.defaults = {
	speed: 'fast',
	times: 2
};
$('#experiment4').supererbox().supererbox('before','move', function() {
	this.element.pulse();
});

// Experiment 5
$('#experiment5').supererbox().supererbox('around','move', function() {
	this.element.pulse();
	this.yield();
	this.element.pulse();
});

</code></pre>
<div><input type="button" id="home" value="Bring Them Home"/></div>
<div class="target" id="experiment1">Experiment 1 (Click Me)</div>
<div class="target" id="experiment2">Experiment 2 (Click Me)</div>
<div class="target" id="experiment3">Experiment 3 (Click Me)</div>
<div class="target" id="experiment4">Experiment 4 (Click Me)</div>
<div class="target" id="experiment5">Experiment 5 (Click Me)</div>
]]></content:encoded>
			<wfw:commentRss>http://youngisrael-stl.org/wordpress/2008/08/22/extending-jquery-ui-widgets-the-final-chapter/feed/</wfw:commentRss>
		</item>
		<item>
		<title>The $.fn.sendkeys Plugin</title>
		<link>http://youngisrael-stl.org/wordpress/2008/08/20/the-fnsendkeys-plugin/</link>
		<comments>http://youngisrael-stl.org/wordpress/2008/08/20/the-fnsendkeys-plugin/#comments</comments>
		<pubDate>Thu, 21 Aug 2008 05:17:44 +0000</pubDate>
		<dc:creator>Danny</dc:creator>
		
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://youngisrael-stl.org/wordpress/?p=114</guid>
		<description><![CDATA[The phone pad below is messed up in Internet Explorer. I know. I don't care anymore. The plugin, however, works.


$(function(){
             $('.output, .test').css({
                fontSize: '100%',
     [...]]]></description>
			<content:encoded><![CDATA[<p>The phone pad below is messed up in Internet Explorer. <a href="/images/webdesign.png">I know</a>. I don't care anymore. The plugin, however, works.</p>
<script src="/inc/jquery.sendkeys.js" type="text/javascript"></script>
<script type="text/javascript">
$(function(){
             $('.output, .test').css({
                fontSize: '100%',
                width: '12em',
                padding: '0.5em'
             });
	$('.phonepad ').css({
		width: '13.5em',
		border: '1px solid gray',
		padding: '0px'
	});
	$('.phonepad input').css({
		width: '3em',
		height: '2em',
		margin: '.5em'
	});
	$('div.test').css({
		border: '1px solid gray'
	});
});
</script>
<pre><code class="language-javascript demo">
	$('div.test input:button').click(function(){
		$('.output').sendkeys($('div.test input:text').val());
	});
	$('.phonepad input').click(function(){
		$('.output').sendkeys(this.name || this.value);
	});
</code></pre>
<pre><code class="language-html demo">
&lt;div&gt;
&lt;textarea class=&quot;output&quot;&gt;&lt;/textarea&gt;
&lt;br/&gt;
&lt;input type=&quot;text&quot; class=&quot;output&quot; /&gt;
&lt;div class=&quot;phonepad&quot;&gt;&lt;input type=&quot;button&quot; name=&quot;{leftarrow}&quot; value=&quot;&amp;larr;&quot;/&gt;&lt;input type=&quot;button&quot; name=&quot;{rightarrow}&quot; value=&quot;&amp;rarr;&quot;/&gt;&lt;input type=&quot;button&quot; name=&quot;{backspace}&quot; value=&quot;BS&quot;/&gt;&lt;input type=&quot;button&quot; value=&quot;7&quot; /&gt;&lt;input type=&quot;button&quot; value=&quot;8&quot; /&gt;&lt;input type=&quot;button&quot; value=&quot;9&quot; /&gt;&lt;input type=&quot;button&quot; value=&quot;4&quot; /&gt;&lt;input type=&quot;button&quot; value=&quot;5&quot; /&gt;&lt;input type=&quot;button&quot; value=&quot;6&quot; /&gt;&lt;input type=&quot;button&quot; value=&quot;1&quot; /&gt;&lt;input type=&quot;button&quot; value=&quot;2&quot; /&gt;&lt;input type=&quot;button&quot; value=&quot;3&quot; /&gt;&lt;input type=&quot;button&quot; value=&quot;*&quot; /&gt;&lt;input type=&quot;button&quot; value=&quot;0&quot; /&gt;&lt;input type=&quot;button&quot; value=&quot;#&quot; /&gt;&lt;/div&gt;
&lt;div class=&quot;test&quot;&gt;&lt;input type=&quot;text&quot; /&gt;&lt;input type=&quot;button&quot; value=&quot;test&quot;/&gt;&lt;/div&gt;
&lt;/div&gt;
</code></pre>
<h4 style="clear:both">The <code>$.fn.sendkeys</code> Plugin</h4>
<p>I wanted to make a general-purpose onscreen keypad, and wasted a huge amount of time trying to find a way to
simulate a keypress. 
<code class="language-javascript">$(element).trigger("keypress",...)</code> won't work. Neither will keyup or keydown.
For security reasons, I guess, you can't tell an element to pretend a key was pressed. The browser is too
worried that you will access menus or something.</p>
<p>So I wrote my own plugin and named it after Microsoft's <a href="http://msdn.microsoft.com/en-us/library/8c6yea83(VS.85).aspx">sendkeys</a> 
which does similar things. For any element <code>elem</code> that
is a <code class="language-html">&lt;textarea&gt;</code> or <code class="language-html">&lt;input type=&quot;text&quot;&gt;</code>, 
<code class="language-javascript">$(elem).sendkeys(string)</code> inserts <code>string</code> at the insertion point or selection. 
It's the insertion point sensitivity
that makes it more sophisticated than <code>elem.value += string</code>.</p>
<span id="more-114"></span>
<p>You can use it on more than one element at a time, like any plugin, but it looks funny, since the insertion point only blinks on the last element (see
the example above).</p>
<p>Internet Explorer (of course!) causes a bit of trouble, since input elements do not retain the location of the insertion point when focus returns to
them. I have to store the insertion point in $.data(elem, 'sendkeys.selection'), which works, but on first use it always appends to the string
rather than inserting.</p>
<p>In the example above, the "test" button will insert whatever is in the text field into the output on top.</p>
<p>It might work on other elements, but there are no guarantees.</p>
<h4>Special keys</h4>
<p>Some special keys are defined, namely <code>{backspace}</code> to delete backwards, <code>{del}</code> to delete forwards, 
and <code>{rightarrow}</code> and <code>{leftarrow}</code> to move the insertion point. <code>{selectall}</code> selects the entire field.
<code>{{}</code> inserts a <code>{</code> by itself.
So 
<code class="language-javascript">$(elem).sendkeys('1234')</code> inserts <code>1234</code>,
<code class="language-javascript">$(elem).sendkeys('123{backspace}4')</code> inserts <code>124</code>, and
<code class="language-javascript">$(elem).sendkeys('1234{leftarrow}{leftarrow}{leftarrow}{del}')</code> inserts <code>134</code>.
</p>
<p>I used Microsoft's key-escaping notation rather than backslashes because putting backslashes in strings means escaping <em>them</em>, and I
always get lost in the forest of slashes. Unlike the Microsoft function, this does not use metacharacters (+^%~).</p>
<h4>Options</h4>
<p>There are no options to the plugin call itself, but the <code>$.fn.sendkeys.defaults</code> object contains the functions to deal with special keys.
It defaults to:</p>
<pre><code class="language-javascript">
$.fn.sendkeys.defaults = {
	'{backspace}': backspace,
	'{rightarrow}': rightarrow,
	'{leftarrow}': leftarrow,
	'{del}': del,
	'{{}': function() {simplechar.call(this, '{')},
	'simplechar': simplechar // the default function
};
</code></pre>
<p>where the <code>backspace</code>, <code>rightarrow</code>, <code>leftarrow</code> and <code>del</code> functions are browser-specific.
You can create synonyms easily, like <code class="language-javascript">$.fn.sendkeys.defaults['{BS}'] = $.fn.sendkeys.defaults['{backspace}']</code>.
<code class="language-javascript">$.fn.sendkeys.defaults.simplechar</code> is the workhorse insertion function. You can define your own special key functions
as <code class="language-javascript">function(&lt;string&gt;)</code>, where the argument is the name of the special key and
<code class="language-javascript">this</code> is bound to the element.<p>
<p>Thus, <code class="language-javascript">$.fn.sendkeys.defaults['{alert}'] = function(s) {alert(this.value}}</code>.</p>
<p>The plugin also pulls custom special keys from the jQuery cache with the key 'sendkeys', so</p>
<pre><code class="language-javascript">
$.data(elem, 'sendkeys', {
	'{alert}' : function(s) {alert(this.value}}
});
</code></pre>
<p>will use that function on that element only.</p>
<h4>Downloads</h4>
<p>Download <a href="/inc/jquery.sendkeys.js">$.fn.sendkeys</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://youngisrael-stl.org/wordpress/2008/08/20/the-fnsendkeys-plugin/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Testing demo insertion</title>
		<link>http://youngisrael-stl.org/wordpress/2008/08/14/testing-demo-insertion/</link>
		<comments>http://youngisrael-stl.org/wordpress/2008/08/14/testing-demo-insertion/#comments</comments>
		<pubDate>Fri, 15 Aug 2008 03:00:45 +0000</pubDate>
		<dc:creator>Danny</dc:creator>
		
		<category><![CDATA[Web Design]]></category>

		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://youngisrael-stl.org/wordpress/?p=102</guid>
		<description><![CDATA[I added some potentially dangerous code to automatically turn code examples (things in &#60;code&#62; elements with class demo into actual HTML or javascript that are added to the post. The javascript part works; I used it in the last post; here's testing the HTML insertion:

  &#60;div style="background: purple; margin: 2px"&#62;This is a test&#60;/div&#62;

And more [...]]]></description>
			<content:encoded><![CDATA[<p>I added some potentially dangerous code to automatically turn code examples (things in <code>&lt;code&gt;</code> elements with class <code>demo</code> into actual HTML or javascript that are added to the post. The javascript part works; I used it in <a href="/wordpress/2008/08/13/extending-jquery-ui-widgets-revisited/">the last post</a>; here's testing the HTML insertion:</p>
<pre><code class="language-html demo">
  &lt;div style="background: purple; margin: 2px"&gt;This is a test&lt;/div&gt;
</code></pre>
<p>And more testing:</p>
<pre><code class="demo language-html">
  &lt;div style="background: #080; margin: 2px"&gt;This is a test&lt;/div&gt;
</code></pre>
]]></content:encoded>
			<wfw:commentRss>http://youngisrael-stl.org/wordpress/2008/08/14/testing-demo-insertion/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Extending jQuery UI Widgets Revisited</title>
		<link>http://youngisrael-stl.org/wordpress/2008/08/13/extending-jquery-ui-widgets-revisited/</link>
		<comments>http://youngisrael-stl.org/wordpress/2008/08/13/extending-jquery-ui-widgets-revisited/#comments</comments>
		<pubDate>Thu, 14 Aug 2008 03:10:06 +0000</pubDate>
		<dc:creator>Danny</dc:creator>
		
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://youngisrael-stl.org/wordpress/?p=81</guid>
		<description><![CDATA[This is an updated version of a tutorial I
wrote a bit back, improved thanks to conversations with Scott Gonzalez
of the jQuery UI team. Thanks!
Avoiding Bloat in Widgets
A while back, Justin Palmer wrote an excellent article on
"Avoiding Bloat in Widgets."
The basic premise (no suprise to anyone whose ever dealt with object-oriented programming) is that your widgets [...]]]></description>
			<content:encoded><![CDATA[<p>This is an updated version of a <a href="/wordpress/2008/08/04/extending-jquery-ui-widgets/">tutorial I
wrote</a> a bit back, improved thanks to conversations with Scott Gonzalez
of the jQuery UI team. Thanks!</p>
<h4>Avoiding Bloat in Widgets</h4>
<p>A while back, Justin Palmer wrote an excellent article on
"<a href="http://alternateidea.com/blog/articles/2006/12/4/avoiding-bloat-in-widgets">Avoiding Bloat in Widgets</a>."
The basic premise (no suprise to anyone whose ever dealt with object-oriented programming) is that your widgets should not
do everything possible; they should do one thing well but be flexible enough to allow others to
modify them.</p>
<p>He describes two ways of extending objects: subclassing and aspect-oriented programming (AOP). Subclassing creates new
classes, while AOP modfies the methods of a single object. Both can be useful.</p>
<span id="more-81"></span>
<p>So let's make Palmer's <code class="language-javascript">Superbox</code> widget (it just moves randomly about the screen with mouse clicks):</p>
<pre><code class="language-javascript demo">
$.yi = {}; // create our namespace
var Superbox = {
	init: function(){
		var self = this;
		this.element.click(function(){
			self.move();
		});
	},
	move: function(){
		this.element.css (this.newPoint());
	},
	newPoint: function(){
		return {top: this.distance(), left: this.distance()};
	},	
	distance: function(){
		return Math.round (Math.random()*this.getData('distance'));
	}
};
$.widget ('yi.superbox', Superbox);
$.yi.superbox.defaults = { distance: 200 };
</code></pre>
<p>I've factored apart a lot of the code, so we have plenty of "hooks" to use to extend the method without
copying code. Note that none of the code refers to "superbox" directly, so we can create subclasses that don't know the superclass's name.</p>
<div class="target" id="experiment1">Experiment 1 (Click Me)</div>
<div><input type="button" id="home1" value="Bring It Home"/></div>
<script>
$(function(){
	$('.target').css({
		position: 'relative',
		background: 'green',
		padding: '5px',
		height: '100px',
		width: '100px',
		color: 'white'
	});
	$('#experiment1').superbox();
	$('#home1').click(function(){
		$('#experiment1').css({top: 0, left:0});
	});
});
</script>

<h4>Subclassing Widgets</h4>
<p>Now let's make a new class, <code class="language-javascript">supererbox</code>, that moves rather than jumps to its new location.
I'll use Douglas Crockford's <a href="http://javascript.crockford.com/prototypal.html">prototypal inheritance pattern</a> to simplify
subclassing (you could use a fancier one like Dean Edward's <a href="http://dean.edwards.name/weblog/2006/03/base/">Base</a>,
or manipulate <code class="language-javascript">prototype</code>s yourself).</p>
<pre><code class="language-javascript demo">
function object(o){
	function F(){};
	F.prototype = o;
	return new F;
}

$.widget.subclass = function (name, superclass){
	$.widget(name); // Slightly inefficient to create a widget only to discard its prototype, but it's not too bad
	name = name.split('.');
	var widget = $[name[0]][name[1]]; // $.widget should return the object itself!
	
	widget.prototype = object(superclass.prototype);
	var args = Array.prototype.slice.call(arguments,1); // get all the add-in methods
	args[0] = widget.prototype;
	$.extend.apply(null, args); // and add them to the prototype
	widget.defaults = object(superclass.defaults);
	
	// Subtle point: we want to call superclass init and destroy if they exist
	// (otherwise the user of this function would have to keep track of all that)
	if (widget.prototype.hasOwnProperty('init')){;
	  var init = widget.prototype.init;
		widget.prototype.init = function(){
			superclass.prototype.init.apply(this);
			init.apply(this);
		}
	};
	if (widget.prototype.hasOwnProperty('destroy')){
		var destroy = widget.prototype.destroy;
		widget.prototype.destroy = function(){
			destroy.apply(this);
			superclass.prototype.destroy.apply(this);
		}
	}
	return widget; // address my complaint above
};

// allow for subclasses to call superclass methods
$.widget.prototype.callSuper = function(superclass, method){
	superclass = superclass.split('.'); // separate namespace and name
	return $[superclass[0]][superclass[1]].prototype[method].apply(this, Array.prototype.slice.call(arguments, 2)); // corrected from (arguments, 3)
};
// For the purposes of this demo, the above function was defined after we created superbox,
// so superbox does not include it. We'll include it manually
$.yi.superbox.prototype.callSuper = $.widget.prototype.callSuper;
</code></pre>
<p>And use it like this:</p>
<pre><code class="language-javascript demo">
$.widget.subclass ('yi.supererbox', $.yi.superbox, {
	// overriding and new methods
	move: function(){
		this.element.animate(this.newPoint(), this.getData('speed'));
	},
	home: function(){
		this.element.animate({top:0, left:0}, this.getData('speed'));
	}
});
$.yi.supererbox.defaults.speed = 'normal';

</code></pre>
<p>The function signature is <code class="language-javascript">$.widget.subclass(name &lt;String&gt;, superclass &lt;Object&gt;, [newMethods &lt;Object&gt;]*)</code>,
where you can use as many newMethod objects as you want. This lets you use mixin objects, like <code class="language-javascript">$.ui.mouse</code>,
that add a specific set of methods.</p>
<p>We now have a new widget called supererbox that is just like superbox but moves smoothly.</p>
<div class="target" id="experiment2">Experiment 2 (Click Me)</div>
<div><input type="button" id="home2" value="Bring It Home"/></div>
<script>
$(function(){
	$('#experiment2').supererbox();
	$('#home2').click(function(){
		$('#experiment2').supererbox('home');
	});
});
</script>
<h4>Calling Superclass Methods</h4>
<p>If we want to use the superclass methods in our method, we use <code class="language-javascript">callSuper</code>:</p>
<pre><code class="language-javascript demo">
$.widget.subclass('yi.superboxwithtext', $.yi.supererbox, {
	move: function(){
		var count = this.getData('count') || 0;
		++count;
		this.setData('count', count);
		this.element.text('Move number '+count);
		this.callSuper('yi.supererbox', 'move'); // note that we could just as well use 'yi.superbox' for the original, "jumpy" move
	}
});
</code></pre>
<div class="target" id="experiment3">Experiment 3 (Click Me)</div>
<div><input type="button" id="home3" value="Bring It Home"/></div>
<script>
$(function(){
	$('#experiment3').superboxwithtext();
	$('#home3').click(function(){
		$('#experiment3').css({top: 0, left: 0}).text('Experiment 3 (Click Me)');
	});
});
</script>

<h4>Aspect Oriented Programming</h4>
<p>Aspect oriented programming addresses some of these problems, by keeping a reference to the superclass method.
New methods don't so much override the old ones as supplement them, adding code before or after (or both) the
original code, without hacking at the original class definition.</p>
<p>We'll create a mixin object for widgets that's stolen straight from Justin Palmer's article:</p>
<pre><code class="language-javascript demo">
$.widget.aspect =  {
  yield: null,
  returnValues: { },
  before: function(method, f) {
    var original = this[method];
    this[method] = function() {
      f.apply(this, arguments);
      return original.apply(this, arguments);
    };
  },
  after: function(method, f) {
    var original = this[method];
    this[method] = function() {
      this.returnValues[method] = original.apply(this, arguments);
      return f.apply(this, arguments);
    }
  },
  around: function(method, f) {
    var original = this[method];
    this[method] = function() {
      this.yield = original;
      return f.apply(this, arguments);
    }
  }
};
</code></pre>
<p>And we use it just like we might use <code class="language-javascript">$.ui.mouse</code>: <code class="language-javascript">$.widget('ns.foo', $.extend({}, {...methods for foo...}, $.widget.aspect)</code>
or, with our subclassing, $.<code class="language-javascript">widget.subclass('ns.foo-with-aspects', $.ns.foo, $.widget.aspect)</code>.</p>
<p>For example, let's say we have a cool plugin to make an element pulsate (I know, UI has a <code class="language-javascript">pulsate</code> method that does this):</p>
<pre><code class="language-javascript demo">
$.fn.pulse = function (opts){
	opts = $.extend ({}, $.fn.pulse.defaults, opts);
	for (i = 0; i &lt; opts.times; ++i){
		this.animate({opacity: 0.1}, opts.speed).animate({opacity: 1}, opts.speed);
	}
	return this;
};
$.fn.pulse.defaults = {
	speed: 'fast',
	times: 2
};
</code></pre>

<p>And we'll create a version of supererbox that allows for AOP:</p>
<pre><code class="language-javascript demo">
$.widget.subclass ('yi.supererbox2', $.yi.supererbox, $.widget.aspect);
</code></pre>
<p>And we'll create a supererbox object, then make it pulse before moving:</p>
<pre><code class="language-javascript demo">
$('#experiment4').supererbox2().supererbox2('before','move', function() {
	this.element.pulse();
});
</code></pre>
<div class="target" id="experiment4">Experiment 4 (Click Me)</div>
<div><input type="button" id="home4" value="Bring It Home"/></div>
<script>
$(function(){
	$('#home4').click(function(){
		$('#experiment4').supererbox2('home');
	});
});
</script>
<p>Or even make it pulse before and after moving:</p>
<pre><code class="language-javascript demo">
$('#experiment5').supererbox2().supererbox2('around','move', function() {
	this.element.pulse();
	this.yield();
	this.element.pulse();
});
</code></pre>
<div class="target" id="experiment5">Experiment 5 (Click Me)</div>
<div><input type="button" id="home5" value="Bring It Home"/></div>
<script>
$(function(){
	$('#home5').click(function(){
		$('#experiment5').supererbox2('home');
	});	
});
</script>
<p>Note that once we added the aspect methods to create supererbox2, we didn't create any new classes to get this new behavior;
we added the behavior to each object after the object was created.</p>]]></content:encoded>
			<wfw:commentRss>http://youngisrael-stl.org/wordpress/2008/08/13/extending-jquery-ui-widgets-revisited/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Testing Chili</title>
		<link>http://youngisrael-stl.org/wordpress/2008/08/10/testing-chili/</link>
		<comments>http://youngisrael-stl.org/wordpress/2008/08/10/testing-chili/#comments</comments>
		<pubDate>Mon, 11 Aug 2008 01:59:41 +0000</pubDate>
		<dc:creator>Danny</dc:creator>
		
		<category><![CDATA[Web Design]]></category>

		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://youngisrael-stl.org/wordpress/?p=54</guid>
		<description><![CDATA[I like the idea of syntax coloring, so let's see if Chili works:

alert('Hello, world');


and another: &#60;div&#62;Hello, &#60;em&#62;world&#60;/em&#62;&#60;/div&#62;

I'm trying to be as HTML5-compliant as possible, at least in the sense of using their standards rather than making up my own, so the Chili setup I'm using is:

    $.extend(ChiliBook, {
     [...]]]></description>
			<content:encoded><![CDATA[<p>I like the idea of syntax coloring, so let's see if <a href="http://noteslog.com/chili/">Chili</a> works:</p>
<pre><code class="language-javascript">
alert('Hello, world');
</code></pre>

<p>and another: <code class="language-html">&lt;div&gt;Hello, &lt;em&gt;world&lt;/em&gt;&lt;/div&gt;</code></p>

<p>I'm trying to be as HTML5-compliant as possible, at least in the sense of using their standards rather than making up my own, so the Chili setup I'm using is:</p>
<pre><code class="language-javascript">
    $.extend(ChiliBook, {
        automatic: false,
        codeLanguage: function(el){
            // use the HTML5 language class
            var recipeName = /language-(\S+)/.exec(el.className);
            return recipeName ? recipeName[1] : &#39;&#39;;
        }
    });
    $(function(){
        $(&#39;code[class*=language-]&#39;).not($('pre code')).chili({lineNumbers: false})
                                  .otherwise().chili({lineNumbers: true});
    });

 </code></pre>
<p>Sweet! The idea of the above code is to look for a class that starts with "language-" and use that as the recipe for Chili (rather than Chili's built-in way of taking the entire className). It also assumes that any code in a <code>pre</code> element should have line numbers, and anything else should not. It uses the cute and brilliant <code>otherwise</code> plugin from
http://groups.google.com/group/jquery-en/browse_thread/thread/6be2a127822a108d.
</p>

<p>Update: It looks like line numbering works only intermittently. Oh well; I won't fix it.</p>]]></content:encoded>
			<wfw:commentRss>http://youngisrael-stl.org/wordpress/2008/08/10/testing-chili/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Namespaces in jQuery</title>
		<link>http://youngisrael-stl.org/wordpress/2008/08/05/namespaces-in-jquery/</link>
		<comments>http://youngisrael-stl.org/wordpress/2008/08/05/namespaces-in-jquery/#comments</comments>
		<pubDate>Tue, 05 Aug 2008 06:44:48 +0000</pubDate>
		<dc:creator>Danny</dc:creator>
		
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://youngisrael-stl.org/wordpress/index.php/2008/08/05/namespaces-in-jquery/</guid>
		<description><![CDATA[jQuery encourages using namespaces for methods in the $ namespace, like $.foo.bar() rather than $.bar(). This works for $ because methods don't expect this to refer to anything specific, and the way javascript works is to assign this to the last-named object, so in $.foo.bar(), this refers to $.foo.
This idea fails for plugins, however, since [...]]]></description>
			<content:encoded><![CDATA[<p>jQuery encourages using namespaces for methods in the <code class="language-javascript">$</code> namespace, like <code class="language-javascript">$.foo.bar()</code> rather than <code class="language-javascript">$.bar()</code>. This works for <code class="language-javascript">$</code> because methods don't expect <code class="language-javascript">this</code> to refer to anything specific, and the way javascript works is to assign <code class="language-javascript">this</code> to the last-named object, so in <code class="language-javascript">$.foo.bar()</code>, <code class="language-javascript">this</code> refers to <code class="language-javascript">$.foo</code>.</p>
<p>This idea fails for plugins, however, since plugins expect <code class="language-javascript">this</code> to refer to the jQuery object that started the chain.
If I define <code class="language-javascript">$.fn.bar = function(){}</code>, then when <code class="language-javascript">$(...).bar()</code> is called, <code class="language-javascript">this</code> refers to <code class="language-javascript">$(...)</code>, just as we want. But if I define <code class="language-javascript">$.fn.foo.bar = function(){}</code>, then when <code class="language-javascript">$(...).foo.bar()</code> is called, <code class="language-javascript">this</code> refers to <code class="language-javascript">$(...).foo</code>, which is an object that knows nothing about jQuery. There's no way to make an object reference return something else.</p>
<p>But all is not lost. We can define a function that returns an object, and that function can use <code class="language-javascript">this</code> to set the returned object to be just like a jQuery object, but with the desired namespaced methods in it. The inefficient way to do that is to copy the new methods into the jQuery object, but if we can manipulate the prototype chain directly (as we can in Firefox) we can add our new methods to the chain without copying.</p>
<span id="more-28"></span>
<p>So a namespacing plugin would be:</p>
<pre><code class="language-javascript">
(function($){
if ({}.__proto__){
	// mozilla  &#038; webkit expose the prototype chain directly
	$.namespace = function(name){
		$.fn[name] = function namespace() { // insert this function in the prototype chain
			this.__proto__ = arguments.callee;
			return this;
		};
		$.fn[name].__proto__ = $.fn;
	};
	$.fn.$ = function(){
		this.__proto__ = $.fn;
		return this;
	};	
}else{
	// every other browser; need to copy methods
	$.namespace = function(name){
		$.fn[name] = function namespace() { return this.extend(arguments.callee); };
	};
	$.fn.$ = function() { // slow but restores the default namespace
		var len = this.length;
		this.extend($.fn);
		this.length = len; // $.fn has length = 0, which messes everything up
		return this;
	};
}
})(jQuery);
</code></pre>
<p>And you could use it like:</p>
<pre><code class="language-javascript">
	$.namespace('danny');
	$.namespace('danny2');
	$.fn.danny.foo = function() {return this.css('color', 'green')};
	$.fn.danny2.foo = function(x){alert(x); return this; };
	// now we have two different methods "foo"
	$('p').danny().foo(); // colors paragraphs green
	$('p').danny2().foo('Hello, world'); // alerts 'Hello, world'
	$('p').danny().foo().danny2().foo('Hello, world'); // chaining works
	$.fn.danny.add = function(a,b) { alert(a+b); return this;}; // defines a function with the same name as a real jQuery one
	$('p').danny().add(1,2).$().add('div'); // the $() plugin restores the real jQuery namespace to a chain
</code></pre>
      
<p>The namespacing is per-chain only; <code class="language-javascript">$('p').danny()</code> does not affect any subsequent statements. Plugins that
call <code class="language-javascript">pushStack</code> will reset the namespacing, but in general the namespace function should be called right before the method, so that should not be an issue.</p>
<p>This is inefficient, obviously, adding an extra function call and possible a lot of copying with <code class="language-javascript">extend</code>, but for most code that is insignificant.</p>]]></content:encoded>
			<wfw:commentRss>http://youngisrael-stl.org/wordpress/2008/08/05/namespaces-in-jquery/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Extending jQuery UI Widgets</title>
		<link>http://youngisrael-stl.org/wordpress/2008/08/04/extending-jquery-ui-widgets/</link>
		<comments>http://youngisrael-stl.org/wordpress/2008/08/04/extending-jquery-ui-widgets/#comments</comments>
		<pubDate>Tue, 05 Aug 2008 02:21:06 +0000</pubDate>
		<dc:creator>Danny</dc:creator>
		
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://youngisrael-stl.org/wordpress/index.php/2008/08/04/extending-jquery-ui-widgets/</guid>
		<description><![CDATA[Update: this post is obsolete. Please see the updated version
Avoiding Bloat in Widgets
A while back, Justin Palmer wrote an excellent article on
"Avoiding Bloat in Widgets."
The basic premise (no suprise to anyone who's ever dealt with object-oriented programming) is that your widgets should not
do everything possible; they should do one thing well but be flexible enough [...]]]></description>
			<content:encoded><![CDATA[<h4>Update: this post is obsolete. Please see <a href="/wordpress/2008/08/13/extending-jquery-ui-widgets-revisited/">the updated version</a></h4>
<h4>Avoiding Bloat in Widgets</h4>
<p>A while back, Justin Palmer wrote an excellent article on
"<a href="http://alternateidea.com/blog/articles/2006/12/4/avoiding-bloat-in-widgets">Avoiding Bloat in Widgets</a>."
The basic premise (no suprise to anyone who's ever dealt with object-oriented programming) is that your widgets should not
do everything possible; they should do one thing well but be flexible enough to allow others to
modify them.</p>
<p>He describes two ways of extending objects: subclassing and aspect-oriented programming (AOP). Subclassing creates new
classes, while AOP modfies the methods of a single object. Both can be useful.</p>
<span id="more-27"></span>
<p>So let's make Palmer's <code>Superbox</code> widget (it just moves randomly about the screen with mouse clicks):</p>
<pre>
var Superbox = {
	init: function(){
		this.element.click(function(){
			$.data(this,'superbox').move();
		});
	},
	move: function(){
		this.element.css (this.newPoint());
	},
	newPoint: function(){
		return {top: this.distance(), left: this.distance()};
	},	
	distance: function(){
		return Math.round (Math.random()*this.getData('distance'));
	}
};
$.widget ('yi.superbox', Superbox);
$.yi.superbox.defaults = { distance: 200 };
</pre>
<p>I've factored apart a lot of the code, so we have plenty of "hooks" to use to extend the method without
copying code. The <code>$.data(this,'superbox')</code> is the idiom to get the widget object from a DOM element.</p>
<div class="target" id="experiment1">Experiment 1 (Click Me)</div>
<div><input type="button" id="home1" value="Bring It Home"/></div>
<script>
$.yi = {}; // $.widget should do this for us!
var Superbox = {
	init: function(){
		this.element.click(function(){
			$.data(this,'superbox').move();
		});
	},
	move: function(){
		this.element.css (this.newPoint());
	},
	newPoint: function(){
		return {top: this.distance(), left: this.distance()};
	},	
	distance: function(){
		return Math.round (Math.random()*this.getData('distance'));
	}
};
$.widget ('yi.superbox', Superbox);
$.yi.superbox.defaults = { distance: 200 };
$(function(){
	$('.target').css({
		position: 'relative',
		background: 'green',
		padding: '5px',
		height: '100px',
		width: '100px',
		color: 'white'
	});
	$('#experiment1').superbox();
	$('#home1').click(function(){
		$('#experiment1').css({top: 0, left:0});
	});
});
</script>

<h4>Subclassing Widgets (The First Try)</h4>
<p>Now let's make a new class, <code>supererbox</code>, that moves rather than jumps to its new location.
I'll use Douglas Crockford's <a href="ref?">prototypal inheritance pattern</a> to simplify
subclassing (you could use a fancier one like Dean Edward's <a href="ref?">base2</a>,
or manipulate <code>prototype</code>s yourself).</p>
<pre>
function object(o){
	function F(){};
	F.prototype = o;
	return new F;
}

// utility function
// if eval weren't evil, it would just be eval('$.'+name);
function widgetNamed(name){
	var name = name.split('.');
	var namespace = name[0];
	name = name[1];
	return $[namespace][name];
}

$.widget.subclass = function (name, superName){
	$.widget(name); // Slightly inefficient to create a widget only to discard its prototype, but it's not too bad
	
	// $.widget ought to return the created object, obviating this call
	var widget = widgetNamed(name);
	var superclass = widgetNamed(superName);
	
	widget.prototype = object(superclass.prototype);
	var args = Array.prototype.slice.call(arguments,1); // get all the add-in methods
	args[0] = widget.prototype;
	$.extend.apply(null, args); // and add them to the prototype
	widget.defaults = object(superclass.defaults);
	return widget; // address my complaint above
};
</pre>
<p>And use it like this:</p>
<pre>
$.widget.subclass ('yi.supererbox', 'yi.superbox', {
	// overriding and new methods
	move: function(){
		this.element.animate(this.newPoint(), this.getData('speed'));
	},
	home: function(){
		this.element.animate({top:0, left:0}, this.getData('speed'));
	}
});
$.yi.supererbox.defaults.speed = 'normal';
</pre>
<p>The function signature is <code>$.widget.subclass(name &lt;String&gt;, superName &lt;String&gt;, [newMethods &lt;Object&gt;]*)</code>,
where you can use as many newMethod objects as you want. This lets you use mixin objects, like <code>$.ui.mouse</code>,
that add a specific set of methods.</p>
<h4>Getting Subclassing Right</h4>
<p>This is pretty good as it stands, but the ever-astute reader will note that there are a number of problems with this method:</p>
<ol>
	<li>Overriding methods replace the superclass methods entirely. There's no
	way to get at the original move if, for some reason, we wanted to call it.</li>
	<li>Methods in the superclass that refer to <code>$.data(this,'superbox')</code> will fail in subclassed
	code. The subclassed objects are attached to <code>$.data(this,'supererbox')</code>. This didn't matter
	in our supererbox example, since we overrode the only method that mentioned superbox itself. But it would be
	a fatal problem it we, e.g., overrode <code>newPoint</code>.</li>
	<li>Subclasses shouldn't have to keep track of constructing and deconstructing their superclasses. As is it,
	a subclass needs to somehow call or copy the superclass <code>init</code> in its own <code>init</code>,
	and the superclass <code>destroy</code> in its own
	<code>destroy</code>. This didn't matter in our example, since we didn't use <code>init</code> or <code>destroy</code>,
	but it could be a big problem.</li>
</ol>
<p>So we add some slightly kludgy code to keep track of all the superclass methods:</p>
<pre>
$.widget.subclass = function (name, superName){
	$.widget(name); // Slightly inefficient to create a widget only to discard its prototype, but it's not too bad
	
	// $.widget ought to return the created object, obviating this call
	var widget = widgetNamed(name);
	var superclass = widgetNamed(superName);

	widget.prototype = object(superclass.prototype);
	var args = Array.prototype.slice.call(arguments,1); // get all the add-in methods
	args[0] = widget.prototype;
	$.extend.apply(null, args); // and add them to the prototype
	widget.defaults = object(superclass.defaults);
	// create the superclass chain, a hash of widget objects indexed by their names
	superName = superName.split('.')[1]; // remove the namespace
	widget.supers =  $.extend({}, superclass.supers); // get the old superclasses
	widget.supers[superName] = superclass; // and add the new
	
	// address the third problem above by making the init method of the subclass call the init method of the superclass
	var init = widget.prototype.hasOwnProperty('init') ? widget.prototype.init : function(){};
	widget.prototype.init = function(){
		this.element.data(superName, this); // address the second problem by adding this under the superclass's name as well
		superclass.prototype.init.apply(this); // address the third problem by calling the superclass's init
		init.apply(this); // do the real init
	};
	// now do the same for destroy, if needed
	if (widget.prototype.hasOwnProperty('destroy')){
		var destroy = widget.prototype.destroy;
		widget.prototype.destroy = function(){
			destroy.apply(this);
			superclass.prototype.destroy.apply(this);
		}
	}
	return widget; // address my complaint above
};

// address the first problem by creating method to call the superclass method
// use as this.callSuper($.yi.superbox, 'foo', arg1, arg2); after mixing in the CallSuper class
var CallSuper = {
	callSuper: function(superclass, method){
		return superclass.prototype[method].apply(this, Array.prototype.slice.call(arguments, 3));
	}
};
</pre>
<script>
function object(o){
	function F(){};
	F.prototype = o;
	return new F;
}

// utility function
// if eval weren't evil, it would just be eval('$.'+name);
function widgetNamed(name){
	var name = name.split('.');
	var namespace = name[0];
	name = name[1];
	return $[namespace][name];
}

$.widget.subclass = function (name, superName){
	$.widget(name); // Slightly inefficient to create a widget only to discard its prototype, but it's not too bad
	
	// $.widget ought to return the created object, obviating this call
	var widget = widgetNamed(name);
	var superclass = widgetNamed(superName);

	widget.prototype = object(superclass.prototype);
	var args = Array.prototype.slice.call(arguments,1); // get all the add-in methods
	args[0] = widget.prototype;
	$.extend.apply(null, args); // and add them to the prototype
	widget.defaults = object(superclass.defaults);
	// create the superclass chain, a hash of widget objects indexed by their names
	superName = superName.split('.')[1]; // remove the namespace
	widget.supers =  $.extend({}, superclass.supers); // get the old superclasses
	widget.supers[superName] = superclass; // and add the new
	
	// address the third problem above by making the init method of the subclass call the init method of the superclass
	var init = widget.prototype.hasOwnProperty('init') ? widget.prototype.init : function(){};
	widget.prototype.init = function(){
		this.element.data(superName, this); // address the second problem by adding this under the superclass's name as well
		superclass.prototype.init.apply(this); // address the third problem by calling the superclass's init
		init.apply(this); // do the real init
	};
	// now do the same for destroy, if needed
	if (widget.prototype.hasOwnProperty('destroy')){
		var destroy = widget.prototype.destroy;
		widget.prototype.destroy = function(){
			destroy.apply(this);
			superclass.prototype.destroy.apply(this);
		}
	}
	return widget; // address my complaint above
};

// address the first problem by creating method to call the superclass method
// use as this.callSuper($.yi.superbox, 'foo', arg1, arg2);
var CallSuper = {
	callSuper: function(superclass, method){
		return superclass.prototype[method].apply(this, Array.prototype.slice.call(arguments, 3));
	}
};
</script>
<script>
$.widget.subclass ("yi.supererbox", "yi.superbox", {
	// overriding and new methods
	move: function(){
		this.element.animate(this.newPoint(), this.getData('speed'));
	},
	home: function(){
		this.element.animate({top:0, left:0}, this.getData('speed'));
	}
});
$.yi.supererbox.defaults.speed = 'normal';
</script>
<p>We now have a new widget called supererbox that is just like superbox but moves smoothly.</p>
<div class="target" id="experiment2">Experiment 2 (Click Me)</div>
<div><input type="button" id="home2" value="Bring It Home"/></div>
<script>
$(function(){
	$('#experiment2').supererbox();
	$('#home2').click(function(){
		$('#experiment2').supererbox('home');
	});
});
</script>
<h4>Calling Superclass Methods</h4>
<p>If we want to use the superclass methods in our method, we mixin the <code>CallSuper</code> object and use <code>callSuper</code>:</p>
<pre>
$.widget.subclass('yi.superboxwithtext', 'yi.supererbox', CallSuper, {
	move: function(){
		var count = this.getData('count') || 0;
		++count;
		this.setData('count', count);
		this.element.text('Move number '+count);
		this.callSuper($.yi.supererbox, 'move'); // note that we could just as well use $.yi.superbox for the original, "jumpy" move
	}
});
</pre>
<script>
$.widget.subclass('yi.superboxwithtext', 'yi.supererbox', CallSuper, {
	move: function(){
		var count = this.getData('count') || 0;
		++count;
		this.setData('count', count);
		this.element.text('Move number '+count);
		this.callSuper($.yi.supererbox, 'move'); // note that we could just as well use $.yi.superbox for the original, "jumpy" move
	}
});
</script>
<div class="target" id="experiment3">Experiment 3 (Click Me)</div>
<div><input type="button" id="home3" value="Bring It Home"/></div>
<script>
$(function(){
	$('#experiment3').superboxwithtext();
	$('#home3').click(function(){
		$('#experiment3').css({top: 0, left: 0}).text('Experiment 3 (Click Me)');
	});
});
</script>

<h4>Aspect Oriented Programming</h4>
<p>Aspect oriented programming addresses some of these problems, by keeping a reference to the superclass method.
New methods don't so much override the old ones as supplement them, adding code before or after (or both) the
original code, without hacking at the original class definition.</p>
<p>We'll create a mixin object for widgets that's stolen straight from Justin Palmer's article:</p>
<pre>
$.widget.aspect =  {
  yield: null,
  returnValues: { },
  before: function(method, f) {
    var original = this[method];
    this[method] = function() {
      f.apply(this, arguments);
      return original.apply(this, arguments);
    };
  },
  after: function(method, f) {
    var original = this[method];
    this[method] = function() {
      this.returnValues[method] = original.apply(this, arguments);
      return f.apply(this, arguments);
    }
  },
  around: function(method, f) {
    var original = this[method];
    this[method] = function() {
      this.yield = original;
      return f.apply(this, arguments);
    }
  }
};
</pre>
<script>
// stolen straight from Justin Palmer
$.widget.aspect =  {
  yield: null,
  returnValues: { },
  before: function(method, f) {
    var original = this[method];
    this[method] = function() {
      f.apply(this, arguments);
      return original.apply(this, arguments);
    };
  },
  after: function(method, f) {
    var original = this[method];
    this[method] = function() {
      this.returnValues[method] = original.apply(this, arguments);
      return f.apply(this, arguments);
    }
  },
  around: function(method, f) {
    var original = this[method];
    this[method] = function() {
      this.yield = original;
      return f.apply(this, arguments);
    }
  }
};
</script>
<p>And we use it just like we might use <code>$.ui.mouse</code>: <code>$.widget('ns.foo', $.extend({}, {...methods for foo...}, $.widget.aspect)</code>
or, with our subclassing, $.<code>widget.subclass('ns.foo-with-aspects', 'ns.foo', $.widget.aspect)</code>.</p>
<p>For example, let's say we have a cool plugin to make an element pulsate (I know, UI has a <code>pulsate</code> method that does this):</p>
<pre>
$.fn.pulse = function (opts){
	opts = $.extend ({}, $.fn.pulse.defaults, opts);
	for (i = 0; i &lt; opts.times; ++i){
		this.animate({opacity: 0.1}, opts.speed).animate({opacity: 1}, opts.speed);
	}
	return this;
};
$.fn.pulse.defaults = {
	speed: 'fast',
	times: 2
};
</pre>
<script>
$.fn.pulse = function (opts){
	opts = $.extend ({}, $.fn.pulse.defaults, opts);
	for (i = 0; i < opts.times; ++i){
		this.animate({opacity: 0.1}, opts.speed).animate({opacity: 1}, opts.speed);
	}
	return this;
};
$.fn.pulse.defaults = {
	speed: 'fast',
	times: 2
};
</script>
<p>And we'll create a version of supererbox that allows for AOP:</p>
<pre>
$.widget.subclass ('yi.supererbox2', 'yi.supererbox', $.widget.aspect);
</pre>
<script>
$.widget.subclass ('yi.supererbox2', 'yi.supererbox', $.widget.aspect);
</script>
<p>And we'll create a supererbox object, then make it pulse before moving:</p>
<pre>
$('#experiment4').supererbox2().supererbox2('before','move', function() {
	this.element.pulse();
});
</pre>
<div class="target" id="experiment4">Experiment 4 (Click Me)</div>
<div><input type="button" id="home4" value="Bring It Home"/></div>
<script>
$(function(){
	$('#experiment4').supererbox2().supererbox2('before','move', function() {
		this.element.pulse();
	});
	$('#home4').click(function(){
		$('#experiment4').supererbox('home');
	});
});
</script>
<p>Or even make it pulse before and after moving:</p>
<pre>
$('#experiment5').supererbox2().supererbox2('around','move', function() {
	this.element.pulse();
	this.yield();
	this.element.pulse();
});
</pre>
<div class="target" id="experiment5">Experiment 5 (Click Me)</div>
<div><input type="button" id="home5" value="Bring It Home"/></div>
<script>
$(function(){
	$('#experiment5').supererbox2().supererbox2('around','move', function() {
		this.element.pulse();
		this.yield();
		this.element.pulse();
	});
	$('#home5').click(function(){
		$('#experiment5').supererbox('home');
	});	
});
</script>
<p>Note that once we added the aspect methods to create supererbox2, we didn't create any new classes to get this new behavior;
we added the behavior to each object after the object was created.</p>
]]></content:encoded>
			<wfw:commentRss>http://youngisrael-stl.org/wordpress/2008/08/04/extending-jquery-ui-widgets/feed/</wfw:commentRss>
		</item>
	</channel>
</rss>
