<?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/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Jonathan Fine's weblog</title>
	<atom:link href="http://jonathanfine.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://jonathanfine.wordpress.com</link>
	<description>A journey from TeX to Python, with some interesting diversions</description>
	<lastBuildDate>Fri, 17 Jul 2009 10:54:18 +0000</lastBuildDate>
	<generator>http://wordpress.com/</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<cloud domain='jonathanfine.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://www.gravatar.com/blavatar/7ba0b113b107ef378ac7d97b96f21283?s=96&#038;d=http://s.wordpress.com/i/buttonw-com.png</url>
		<title>Jonathan Fine's weblog</title>
		<link>http://jonathanfine.wordpress.com</link>
	</image>
			<item>
		<title>Explicit use of JavaScript&#8217;s global object</title>
		<link>http://jonathanfine.wordpress.com/2009/07/17/explicit-use-of-javascripts-global-object/</link>
		<comments>http://jonathanfine.wordpress.com/2009/07/17/explicit-use-of-javascripts-global-object/#comments</comments>
		<pubDate>Fri, 17 Jul 2009 10:54:18 +0000</pubDate>
		<dc:creator>jonathanfine</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://jonathanfine.wordpress.com/?p=67</guid>
		<description><![CDATA[A lot of JavaScript programmers use an anonymous function at the top level, to establish a scope. This allows variables to be defined in a file (or module if your prefer), without adding anything to the global namespace.
The problem with this, however, it that it becomes awkward when you do need to add something to [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=jonathanfine.wordpress.com&blog=1748602&post=67&subd=jonathanfine&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>A lot of JavaScript programmers use an anonymous function at the top level, to establish a scope. This allows variables to be defined in a file (or module if your prefer), without adding anything to the global namespace.</p>
<p>The problem with this, however, it that it becomes awkward when you do need to add something to the global namespace.</p>
<p>Here&#8217;s a trick that solves this problem.</p>
<pre>    (function()
    {
        var global = (function(){return this;}).call();
        global.Formula = function (){
            // body of function
        };
    })();</pre>
<p>This code is equivalent to:</p>
<pre>    var Formula;
    (function()
    {
        Formula = function (){
            // body of function
        };
    })();</pre>
<p>Both forms have the same number of lines of code, but the first pulls ahead for each additional object added to the global namespace.  But there are other advantages.</p>
<ul>
<li>It is made explicit, that the assignment to Formula is being made in the global namespace.</li>
<li>Suppose you decide that Formula and its companions should live in a different namespace.  In the first, simply search and replace on &#8216;global&#8217; and replace the definition of global.</li>
<li>In the first, we take care to explicitly obtain the object we are changing, namely the global object.</li>
<li>According to Douglas Cockcroft, &#8220;JavaScript&#8217;s global object [...] is far and away the worst part of JavaScript&#8217;s many bad parts&#8221;. Writing as in the first example discourages and makes explicit the use of the global object.</li>
</ul>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/jonathanfine.wordpress.com/67/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/jonathanfine.wordpress.com/67/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/jonathanfine.wordpress.com/67/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/jonathanfine.wordpress.com/67/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/jonathanfine.wordpress.com/67/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/jonathanfine.wordpress.com/67/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/jonathanfine.wordpress.com/67/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/jonathanfine.wordpress.com/67/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/jonathanfine.wordpress.com/67/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/jonathanfine.wordpress.com/67/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=jonathanfine.wordpress.com&blog=1748602&post=67&subd=jonathanfine&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://jonathanfine.wordpress.com/2009/07/17/explicit-use-of-javascripts-global-object/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/242d7f27bd60774efd964dbe680aacda?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">jonathanfine</media:title>
		</media:content>
	</item>
		<item>
		<title>Is JavaScript&#8217;s new syntactic sugar?</title>
		<link>http://jonathanfine.wordpress.com/2009/07/12/is-javascripts-new-syntactic-sugar/</link>
		<comments>http://jonathanfine.wordpress.com/2009/07/12/is-javascripts-new-syntactic-sugar/#comments</comments>
		<pubDate>Sun, 12 Jul 2009 15:24:36 +0000</pubDate>
		<dc:creator>jonathanfine</dc:creator>
				<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://jonathanfine.wordpress.com/?p=63</guid>
		<description><![CDATA[JavaScript has a &#8216;new&#8217; operator for creating objects.  Each object in JavaScript has a hidden pointer to a prototype object, from which it inherits properties.  This pointer is set when the object is created, and cannot be changed during the lifetime of the object.
When &#8216;new&#8217; is used, an object is created that has [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=jonathanfine.wordpress.com&blog=1748602&post=63&subd=jonathanfine&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>JavaScript has a &#8216;new&#8217; operator for creating objects.  Each object in JavaScript has a hidden pointer to a prototype object, from which it inherits properties.  This pointer is set when the object is created, and cannot be changed during the lifetime of the object.</p>
<p>When &#8216;new&#8217; is used, an object is created that has other than the usual default Object prototype object.</p>
<p>From &#8216;new&#8217; we can define a function create(proto) that returns an object whose prototype object is &#8216;proto&#8217;. (I first saw this in Douglas Cockcroft&#8217;s book <em>JavaScript: The Good Parts</em>, but he calls it &#8216;beget&#8217;.)</p>
<p>Conversely, from &#8216;create&#8217; we can define a function, say &#8216;New&#8217; that has the same functionality as the &#8216;new&#8217; operator.  (In JavaScript &#8216;new&#8217; is a keyword, whose meaning can be changed.)</p>
<p>The &#8216;create&#8217; operator is in some sense simpler than the &#8216;new&#8217; operator, but each can be defined in terms of the other.  According to Wikipedia, <a href="http://en.wikipedia.org/wiki/Syntactic_sugar">syntactic sugar</a> &#8220;is syntax designed to make things easier to read or to express, while alternative ways of expressing them exist&#8221;.</p>
<p>I think &#8216;create&#8217; is simpler to use and understand than &#8216;new&#8217;, and so I don&#8217;t regard it as syntactic sugar for the creation creation of objects.  The same Wikipedia term also suggests the term  <em><span>syntactic saccharin</span></em><span> for </span><em>gratuitous syntax which does not actually make programming easier</em>.  I consider &#8216;new&#8217; to be syntactic saccharin.</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/jonathanfine.wordpress.com/63/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/jonathanfine.wordpress.com/63/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/jonathanfine.wordpress.com/63/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/jonathanfine.wordpress.com/63/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/jonathanfine.wordpress.com/63/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/jonathanfine.wordpress.com/63/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/jonathanfine.wordpress.com/63/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/jonathanfine.wordpress.com/63/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/jonathanfine.wordpress.com/63/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/jonathanfine.wordpress.com/63/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=jonathanfine.wordpress.com&blog=1748602&post=63&subd=jonathanfine&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://jonathanfine.wordpress.com/2009/07/12/is-javascripts-new-syntactic-sugar/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/242d7f27bd60774efd964dbe680aacda?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">jonathanfine</media:title>
		</media:content>
	</item>
		<item>
		<title>Javascript and skeletons</title>
		<link>http://jonathanfine.wordpress.com/2009/02/09/javascript-and-skeletons/</link>
		<comments>http://jonathanfine.wordpress.com/2009/02/09/javascript-and-skeletons/#comments</comments>
		<pubDate>Mon, 09 Feb 2009 20:52:15 +0000</pubDate>
		<dc:creator>jonathanfine</dc:creator>
				<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://jonathanfine.wordpress.com/?p=57</guid>
		<description><![CDATA[Here&#8217;s an analogy (and I don&#8217;t know how useful it is).  It&#8217;s about writing JavaScript for web pages.
A beetle, for example, has a hard external skeleton, to which everything else is attached.  A cat, for example, has a hard internal skeleton, to which everything else is attached.  A cat is soft outside [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=jonathanfine.wordpress.com&blog=1748602&post=57&subd=jonathanfine&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>Here&#8217;s an analogy (and I don&#8217;t know how useful it is).  It&#8217;s about writing JavaScript for web pages.</p>
<p>A beetle, for example, has a hard external skeleton, to which everything else is attached.  A cat, for example, has a hard internal skeleton, to which everything else is attached.  A cat is soft outside (although with teeth and claws) while a beetle is soft inside.</p>
<p>So what&#8217;s this got to do with JavaScript and HTML?  Well, a simple HTML page spruced up with some JavaScript for say form entry is a bit like a beetle, where  the HTML is the hard external skeleton.</p>
<p>But a  complex web page, constructed mostly from JavaScript and Ajax supplied data is something else.  It&#8217;s too big and complex to be supported just by HTML and the DOM.  It needs some sort of skeleton.  And so perhaps should be built more like a cat.<br />
<span id="more-57"></span></p>
<p>This is not a new idea.  The famous Model-View-Controller design pattern requires three independent but linked components.  And to my way of thinking, the Model is like the skeleton.</p>
<p>Whether or not you like the analogy, you can ask this: Does my application have a major component that can function relying on HTML and the DOM?   My view is that for complex things this is the way to go, rather than hanging everything on the DOM.</p>
<p>Here&#8217;s another analogy.  A modern web framework, such as Django or Rails, has something like a skeleton, and then templates can be used to add presentational logic and preferences.  This is so different from the old CGI-script way of doing these things. </p>
<p>With a modern web-framework, generating the HTML is an important but external task.  The generated HTML is like the soft skin of an animal.  (Yes, even the rhinoceros has soft skin, although not like a baby.)  The web-framework helps provide a good part of the skeleton. </p>
<p>There&#8217;s a shift in attitudes and culture required to go from writing HTML web pages to writing a modern web application.  Perhaps a similar shift is beginning to happen in the writing of the JavaScript side.  The Google Web Toolkit is a good example of this culture shift.</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/jonathanfine.wordpress.com/57/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/jonathanfine.wordpress.com/57/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/jonathanfine.wordpress.com/57/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/jonathanfine.wordpress.com/57/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/jonathanfine.wordpress.com/57/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/jonathanfine.wordpress.com/57/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/jonathanfine.wordpress.com/57/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/jonathanfine.wordpress.com/57/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/jonathanfine.wordpress.com/57/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/jonathanfine.wordpress.com/57/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=jonathanfine.wordpress.com&blog=1748602&post=57&subd=jonathanfine&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://jonathanfine.wordpress.com/2009/02/09/javascript-and-skeletons/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/242d7f27bd60774efd964dbe680aacda?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">jonathanfine</media:title>
		</media:content>
	</item>
		<item>
		<title>TUG board election</title>
		<link>http://jonathanfine.wordpress.com/2009/01/31/tug-board-election/</link>
		<comments>http://jonathanfine.wordpress.com/2009/01/31/tug-board-election/#comments</comments>
		<pubDate>Sat, 31 Jan 2009 21:01:40 +0000</pubDate>
		<dc:creator>jonathanfine</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://jonathanfine.wordpress.com/?p=50</guid>
		<description><![CDATA[I&#8217;m standing for the board of the TeX Users Group. You&#8217;re invited to make comments on my election statement below.
I work for the Open University (the UK&#8217;s leading provider of distance education) as a TeX expert for print media.  I&#8217;m also halfway
through a two-year project on putting mathematics on web pages.
In 2006&#8211;7 I set [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=jonathanfine.wordpress.com&blog=1748602&post=50&subd=jonathanfine&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>I&#8217;m standing for the board of the TeX Users Group. You&#8217;re invited to make comments on my election statement below.</p>
<p>I work for the Open University (the UK&#8217;s leading provider of distance education) as a TeX expert for print media.  I&#8217;m also halfway<br />
through a two-year project on putting mathematics on web pages.</p>
<p>In 2006&#8211;7 I set up MathTran, which now provides typesetting of<br />
TeX-notation formulas to images as a public web service, serving<br />
about a million images a month.</p>
<p>MathTran shows the value of TeX as a web service, which I&#8217;d like to<br />
extend to whole documents.  Installing and configuring TeX can be<br />
slow and difficult.  Using TeX through a web browser will help<br />
beginners.</p>
<p>Part of my math-on-web project is a page where students can<br />
interactively create a TeX-notation formula, say for putting on a web<br />
page or in a word-processor document.</p>
<p>I have a doctorate in Mathematics and although not my career I still<br />
have research interests. I have been using TeX for over 20 years,<br />
and joined TUG in 1989.  For the past two years I&#8217;ve been Chair of the<br />
UK TeX Users Group, and have recently been re-elected for another<br />
two years.</p>
<p>The past three years have seen UK TUG come out of a long period of<br />
inactivity and decline.  The credit for this of course belongs to the<br />
Committee and the members, and not simply myself.  We&#8217;ve organised<br />
three successful meetings, adopted a new constitution, and set up a<br />
website with links to UK TeX resources.</p>
<p>As a board member I would bring to TUG a focus on a key core<br />
community, namely those who write material with lots of mathematics.<br />
I have a particular interest in providing help and support,<br />
particularly through web pages.</p>
<p>TUG, by virtue of TeX being a typesetting program, rightly has a<br />
focus on print media.  But to flourish we must also use new media<br />
effectively.  The Open University faces the same challenge, and my<br />
experience there will help TUG.</p>
<p>TUG has a special responsibility, to publicise TeX and related<br />
fonts, programs, documentation and other resources.</p>
<p>I&#8217;d like TUG to offer more to institutional members.  In particular,<br />
we should help them share user support experience and resources.<br />
Supporting TeX can be daunting without outside help.</p>
<p>When I joined TUG there were over 150 institutional members. There are<br />
now just 27. The loss I feel the most is the Library of Congress.</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/jonathanfine.wordpress.com/50/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/jonathanfine.wordpress.com/50/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/jonathanfine.wordpress.com/50/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/jonathanfine.wordpress.com/50/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/jonathanfine.wordpress.com/50/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/jonathanfine.wordpress.com/50/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/jonathanfine.wordpress.com/50/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/jonathanfine.wordpress.com/50/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/jonathanfine.wordpress.com/50/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/jonathanfine.wordpress.com/50/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=jonathanfine.wordpress.com&blog=1748602&post=50&subd=jonathanfine&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://jonathanfine.wordpress.com/2009/01/31/tug-board-election/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/242d7f27bd60774efd964dbe680aacda?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">jonathanfine</media:title>
		</media:content>
	</item>
		<item>
		<title>Implementing super in JavaScript</title>
		<link>http://jonathanfine.wordpress.com/2008/09/21/implementing-super-in-javascript/</link>
		<comments>http://jonathanfine.wordpress.com/2008/09/21/implementing-super-in-javascript/#comments</comments>
		<pubDate>Sun, 21 Sep 2008 14:17:37 +0000</pubDate>
		<dc:creator>jonathanfine</dc:creator>
				<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://jonathanfine.wordpress.com/?p=26</guid>
		<description><![CDATA[The problem
JavaScript has objects and what is called prototypal inheritance, but it does not have built-in support for many features provided by other languages.  In particular, it does not have built-in support for classes and instances. Nor does it have built-in support for methods of one class to call super-class methods.
Here is an example. [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=jonathanfine.wordpress.com&blog=1748602&post=26&subd=jonathanfine&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><h2>The problem</h2>
<p>JavaScript has objects and what is called <em>prototypal inheritance</em>, but it does not have built-in support for many features provided by other languages.  In particular, it does not have built-in support for classes and instances. Nor does it have built-in support for methods of one class to call super-class methods.</p>
<p>Here is an example.  Class C is a subclass of class B, and both have an <em>init</em> method.  We would like the <em>init</em> method of Class C to be able to call the <em>init</em> method of class B. In other words, when writing <em>init </em>for class C, we wish to call the super-class <em>init</em> method. Note that class B might in fact be a subclass of class A, and that B might inherit <em>init </em>from A, and not have an <em>init </em>method of its own.</p>
<p>This post of focussed in the single topic of providing access to super-class.  It does not for instance cover how to provide support for class hierarchies and how to manage instance creation.</p>
<h2>Motivation</h2>
<p>Over the past few days I&#8217;ve been trying to understand <a href="http://ejohn.org">John Resig</a>&#8217;s post on <a href="http://ejohn.org/blog/simple-javascript-inheritance/">Simple JavaScript Inheritance</a>, on both the technical and the practical levels. John&#8217;s goal was to <em>extract the soul</em> of the implementations of classical inheritance in <a href="http://code.google.com/p/base2/">base2</a> and <a href="http://prototypejs.org/">Prototype</a>, and to present them as a stand-alone package.</p>
<p>Well, I&#8217;ve not succeeded, but I do understand the problem better.  In particular, I couldn&#8217;t get a clear understanding of what his _super method did.  So to help me understand I set out to write my own.  And this is what I came up with.</p>
<p>I hope in a later post to compare the two approaches.  Be warned that this post is unavoidable quite technical, and that if you&#8217;re a JavaScript novice you&#8217;ll learn a lot if you manage to understand it all.</p>
<p><span id="more-26"></span></p>
<h2>Setting up inheritance</h2>
<p>First we have some code that sets up A, B and C, which are what we can think of as classes, and also c, which we can think of as an instance of C.  (This way of thinking is not shared with the computer.  So far as the program is concerned, the relationship between B and C is exactly the same as that between C and c.  But to our mind one is subclass and the other is instance.)</p>
<pre>var fromProto = function(proto){
    var f = function(){
        this.proto = proto;
    };
    f.prototype = proto;
    return new f();
};

// 'Classes':  A &lt;- B &lt;- C
var base = {};
var A = fromProto(base);
var B = fromProto(A);
var C = fromProto(B);

// Test object - 'Instance': C &lt;- c.
var c = fromProto(C);</pre>
<p>The function fromProto creates an object whose <em>prototype object</em> is &#8216;proto&#8217;.  It also records that fact.  (There are other, implicit, ways in which this fact may be recorded.  But for clarity, here we will make it explicit.)  I learnt about this way of doing things from <a href="http://www.crockford.com">Douglas Crockford&#8217;</a>s book <a href="http/www.amazon.com/exec/obidos/ASIN/0596517742/wrrrldwideweb">JavaScript: The Good Parts</a>.</p>
<h2>Setting up methods</h2>
<p>So that we can test our implementation, we will create some methods.  We will give A methods getA and setA that get and set an &#8216;a&#8217; attribute on the object.  Similarly, we will give B methods getB and setB (that this time get and set a &#8216;b&#8217; attribute).  Once we have done this, c.getA for example will access the A method, because of the usual operation of prototypal inheritance.</p>
<p>To that we really are fetching super-class methods, we will add to C <em>spoiler methods </em>getA, setA, getB and setB.  When called, these spoiler will raise an error. We will also add spoilers getB and setB to A.</p>
<p>To shorten and clarify the code, we introduce a couple of factory functions, for creating get and set methods.</p>
<pre>var _get = function(key){
    return function(){
        return this[key];
    };
};

var _set = function(key){
    return function(value){
        this[key] = value;
    };
};</pre>
<p>And now we can very simple set up the access methods and the spoilers.</p>
<pre>A.getA = _get('a');
A.setA = _set('a');

B.getB = _get('b');
B.setB = _set('b');

// Spoilers - will not be called.
C.getA = C.setA =
    C.getB = C.setA =
    A.getB = A.setB =
    function(){
        ddt();
    };</pre>
<h2>Low-level access to super-class methods</h2>
<p>Here we use only JavaScript primitives to access super-class methods.  We don&#8217;t define and use functions of our own (we&#8217;ll do that later).  In fact, the code below tells up what primitive commands the functions we define must call.</p>
<p>We wish to call the method A.getA, but with the special <em>this</em> object being the object c.  If it were not for C have the spoiler method C.getA, we could write c.getA() to call A.getA with <em>this </em>being c.  But the spoiler is there, so we have to do something else.</p>
<p>JavaScript has <em>apply </em>and <em>call </em>methods precisely for dealing with this problem.  They allow us to specify the object that is to be bound to <em>this</em> during the method call.  More exactly (and this has to be fully understood to follow the rest of this post) both of the function calls below:</p>
<pre>    fn.apply(that, [arg0, arg1, arg2, ...])
    fn.call(that, arg0, arg1, arg2, ...)</pre>
<p>are equivalent to</p>
<pre>    fn(arg0, arg1, arg2, ...)</pre>
<p>except that in this function call <em>this </em>is bound to the value of <em>that</em>.</p>
<p>This, <em>apply</em> and <em>call</em> are exactly what we want.  Moreover, JavaScript does not provide any other method for doing this.  We are obliged to use <em>apply</em> or <em>call. </em>We have not choice here, except which to use.  (We&#8217;ll have more choice later, in how to package our call in functions of our own devising.)</p>
<h2>Using <em>call</em> to access super-class methods</h2>
<p>We can now write and run our first test function.</p>
<pre>C.test1 = function(){

    // Understanding proto.
    C.proto === B || ddt();

    // Here's how to call set.
    C.proto.setA.call(this, 'a1');
    C.proto.setB.call(this, 'b1');

    // Check that set worked.
    this.a = 'a1' || ddt();
    this.b = 'b1' || ddt();

    // Call get, and check that it worked.
    C.proto.getA.call(this) === 'a1' || ddt();
    C.proto.getB.call(this) === 'b1' || ddt();
};

c.test1();</pre>
<p>The code above runs without error. Note that we use C.proto to access the inheritance chain, rather than use our knowledge that C.proto is in fact B.</p>
<h2>Why we need a sweeter syntax</h2>
<p>The above code works, and is perhaps optimal for execution time.  (If as is likely we knew that C.proto.getA was not going to change, we could do this calculation outside the method body and use a cached result to make it run quicker.)</p>
<p>But it far from optimal for programmer productivity.  There are several aspects to this:</p>
<ul>
<li>It is not immediately obvious that we are calling a super-class method.</li>
<li>The code is tricky to write.</li>
<li>The code depends on an implementation detail &#8211; the use of proto to hold the prototypal object.</li>
<li>The code contains a gotcha &#8211; omit <em>call</em> and it silently fails.</li>
</ul>
<p>Some more on the gotcha.  The line of code</p>
<pre>    C.proto.setA(this, 'a1');    // Gotcha! You forgot the call!</pre>
<p>first resolves C.proto to B, and then B.setA to the function A.setA.  It then calls A.setA with arguments the value of <em>this</em> (which is the test object c) and the string &#8216;a1&#8242;.  And now for the gotcha.  In this function call, <em>this</em> is bound to the previous value of <em>this</em> (and the argument &#8216;a1&#8242; is ignored).  Therefore, in this particular case, the above line of code has the same effect as</p>
<pre>    B.a = c;</pre>
<p>which is not at all what is wanted.</p>
<p>We don&#8217;t want traps like this lying so close to the code we are writing.  We want to focus, so to speak, on the road rather than the potholes.  We need a sweeter syntax.  (And should performance be an issue, we can later unwind the sweeter syntax into the primitive operations presented earlier.)</p>
<h2>A sweeter syntax</h2>
<p>Here we have some choices. We wish to sweeten the previous syntax.  Let&#8217;s recall what we have</p>
<pre>    C.proto.setA.call(this, 'a1');</pre>
<p>Now we have to choose.  My choice is</p>
<pre>    sup(C, 'setA')(this, 'a2');</pre>
<p>Notice that sup(C, &#8217;setA&#8217;) is a drop-in replacement for C.proto.setA.call.  This is why I like it. (I chose &#8217;sup&#8217; because we can&#8217;t use &#8217;super&#8217;, which is a reserved word in JavaScript.  It is one of the many reserved words in  JavaScript, that are not actually used in the language.)</p>
<p>Although this is my present choice, I hope that I&#8217;m open to persuasion and learning from experience.  I also believe that going along with the majority is sometimes (not always) the best thing for the community. So if the choice of syntax matters to you, please speak up.</p>
<h2>High-level access to super-class methods</h2>
<p>We&#8217;ll now rewrite the low-level test using the sweeter syntax.  Here it is:</p>
<pre>C.test2 = function(){

    // Here's how to call set.
    sup(C, 'setA')(this, 'a2');
    sup(C, 'setB')(this, 'b2');

    // Check that set worked.
    this.a === 'a2' || ddt();
    this.b === 'b2' || ddt();

    // Call get, and check that it worked.
    sup(C, 'getA')(this) === 'a2' || ddt();
    sup(C, 'getB')(this) === 'b2' || ddt();
};</pre>
<p>Before we can run this test, we need to implement the &#8217;sup&#8217; function.</p>
<h2>Implementation of <em>sup</em></h2>
<p>Recall that</p>
<pre>    sup(C, 'setA')(this, 'a2');</pre>
<p>is to be equivalent to</p>
<pre>    C.proto.setA.call(this, 'a1');</pre>
<p>Here&#8217;s the definition of <em>sup</em>.  I find it the hardest piece of code to understand in this post.  I think you have to see it first, and then work through understanding it.</p>
<pre>var sup = function(klass, name){
    return function(){
        var fn = klass.proto[name];
        return Function.call.apply(fn, arguments);
    };
};</pre>
<p>So let&#8217;s go through it, step by step.</p>
<ol>
<li>The <em>sup</em> function returns a function. This is good. We will be calling this function with, say, c and &#8216;a1&#8242; as arguments. For now, let&#8217;s call this function supSetA.</li>
<li>The function supSetA has set up a closure (we won&#8217;t explain here what that is) and as a result <em>klass</em> and <em>name </em>have within supSetA the values that were originally supplied.  (By the way, &#8216;class&#8217; a reserved word in JavaScript that is not used, just like &#8217;super&#8217;. So we use &#8216;klass&#8217; instead.)</li>
<li>Executing supSetA sets fn to the function A.setA, exactly as before.  (We don&#8217;t move that calculation outside the definition of the returned function.  Our focus is on programmer productivity, and we can&#8217;t be sure that we&#8217;re able to safely cache this value.)</li>
<li>We now execute Function.call.apply(fn, arguments), which is so complicated we&#8217;ll give its explanation all by itself.</li>
</ol>
<h2>The <em>Function.call.apply </em>pattern</h2>
<p>I&#8217;m fairly confident that I&#8217;m the first person to publish code that uses this pattern.  (To check, I did <a href="http://www.google.com/search?q=%22Function.call.apply%22">this Internet search</a> and also <a href="http://www.google.com/codesearch?q=%22function.call.apply%22">this one</a> for the string &#8216;Function.call.apply&#8217;. At the time of writing, they produced 19 hits, none of which coincide with our use.)  So if you&#8217;re an early reader, you might be the second person on earth to know about this pattern. Don&#8217;t be surprised if takes you a little while &#8211; it took me about an hour!</p>
<p>Let&#8217;s unpack the pattern.  We have</p>
<pre>    Function.call.apply(fn, arguments);</pre>
<p>Here goes:</p>
<ol>
<li>Recall that <em>myfunc.apply(obj, [arg1, arg2, arg3, ...)</em> will execute <em>myfunc(arg1, arg2, arg3, ...)</em>, but <strong>with <em>this</em> set equal to <em>obj</em></strong>.</li>
<li>In our case we have
<ol>
<li><em>myfunc</em> is  <em>call.</em></li>
<li><em>obj</em> is the function  <em>A.setA</em>.</li>
<li><em>arguments</em> is <em>[c, 'a2']</em>.</li>
</ol>
</li>
<li>So now we have <em>call(c, &#8216;a2&#8242;)</em>, but <strong>with <em>this</em> set equal to <em>C.proto.setA</em></strong> (which is equal to <em>A.setA</em>).</li>
<li>Recall that previously we used the low-level code <em>C.proto.setA.call(this, &#8216;a2&#8242;)</em> where <em>this </em>is <em>c</em>.</li>
<li>Now for the hard bit. In (4), we are running <em>call</em>(<em>c, &#8216;a2&#8242;</em>), but <strong>with <em>this</em> set equal to <em>C.proto.setA</em></strong>. (Please take some time to think about this. It follows from the rules as to how <em>this</em> is determined.)</li>
<li>Now for the easy bit. Steps 3 and 5 are identical, and so give the same result.  This is what we wanted to see.</li>
</ol>
<h2>Conclusion</h2>
<p>This has been a long and technically demanding post.  As stated earlier, I hop to discuss the relation to other approached in another post.</p>
<p>I&#8217;m optimistic that most of the ideas in this post will make their way into at least one future JavaScript classical inheritance framework.</p>
<p>At the same time, I&#8217;m bearing in mind Douglas Cockcroft&#8217;s <a href="http://javascript.crockford.com/inheritance.html">warning</a>:</p>
<blockquote><p>I have been writing JavaScript    for 8 years now, and I have never once found need to use an <code>uber</code> function. The <var>super</var> idea is fairly important in the classical    pattern, but it appears to be unnecessary in the prototypal and functional    patterns. I now see my early attempts to support the classical model in    JavaScript as a mistake.</p></blockquote>
<p>My view (based on about 18 months experience of JavaScript) is that there&#8217;s room for improvement in the way in which we handle inheritance.  I learned a lot about JavaScript when authoring this post, and I hope that it will also help others.</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/jonathanfine.wordpress.com/26/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/jonathanfine.wordpress.com/26/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/jonathanfine.wordpress.com/26/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/jonathanfine.wordpress.com/26/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/jonathanfine.wordpress.com/26/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/jonathanfine.wordpress.com/26/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/jonathanfine.wordpress.com/26/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/jonathanfine.wordpress.com/26/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/jonathanfine.wordpress.com/26/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/jonathanfine.wordpress.com/26/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=jonathanfine.wordpress.com&blog=1748602&post=26&subd=jonathanfine&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://jonathanfine.wordpress.com/2008/09/21/implementing-super-in-javascript/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/242d7f27bd60774efd964dbe680aacda?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">jonathanfine</media:title>
		</media:content>
	</item>
		<item>
		<title>Data objects in JavaScript</title>
		<link>http://jonathanfine.wordpress.com/2008/09/20/data-objects-in-javascript/</link>
		<comments>http://jonathanfine.wordpress.com/2008/09/20/data-objects-in-javascript/#comments</comments>
		<pubDate>Sat, 20 Sep 2008 15:49:54 +0000</pubDate>
		<dc:creator>jonathanfine</dc:creator>
				<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://jonathanfine.wordpress.com/?p=16</guid>
		<description><![CDATA[The Problem
Suppose we want to count the words in a document, or the identifiers in a computer program.  We&#8217;ll need to keep a dictionary (aka hash or mapping) whose keys are the words and whose values are their frequencies.  When we come across a new word (or identifier) we add it to the [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=jonathanfine.wordpress.com&blog=1748602&post=16&subd=jonathanfine&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><h2>The Problem</h2>
<p>Suppose we want to count the words in a document, or the identifiers in a computer program.  We&#8217;ll need to keep a dictionary (aka hash or mapping) whose keys are the words and whose values are their frequencies.  When we come across a new word (or identifier) we add it to the dictionary as a key, with value equal to one.  When we meet a word already in the dictionary, we increase the value by one.</p>
<p>The starting point, of course, is an empty dictionary (or mapping or hash or whatever you want to call it).  In JavaScript creating one of these requires some thought, and seems not to have been done before.  Here&#8217;s the problem.  In JavaScript we have to store the data (key-value pairs) in an object, and every object comes with some builtin methods.  Here&#8217;s some command-line JavaScript:</p>
<pre>js&gt; data = {};  // Create empty data object, we hope.
js&gt; data.foo === undefined; // true
js&gt; data['foo'] === undefined;  // true
js&gt; data['constructor'] === undefined; // false - not what we want.</pre>
<p><span id="more-16"></span></p>
<h2>Explanation</h2>
<p>JavaScript has what is called <em>prototypical inheritance</em>.  This means that every JavaScript object has a prototype object, and that the original object inherits from the prototype object.  Let&#8217;s call them <em>obj</em> and <em>prot</em> respectively.  If we look up &#8216;obj.foo&#8217; and this fails, then we try &#8216;prot.foo&#8217; and if found use that instead.  And if &#8216;prot.foo&#8217; fails we look up &#8216;protprot.foo&#8217; (where &#8216;protprot&#8217; is the prototype object of &#8216;prot&#8217;) and so on, until we get to the end of the prototype chain.</p>
<p>As it happens, Object.prototype is the prototype object for data, and Object.prototype has a &#8216;constructor&#8217; attribute.  This is why <em>data </em>has a &#8216;constructor&#8217; entry.  It has some others, such as a &#8216;toString&#8217; method.</p>
<h2>Solution</h2>
<p>A probably dangerous solution is to change Object.prototype, because this would change the behaviour of all objects, and would probably break a lot of scripts.  Perhaps better is to create a new sort of object, which masks the unwelcome builtin attributes.  Here&#8217;s the code to do this.</p>
<pre>var Data = function(){};

Data.prototype = {
    // Note: 'for in' does not pick up builtin properties.
    'constructor': undefined,
    'hasOwnProperty': undefined,
    'isPrototypeof': undefined,
    'propertyisEnumerable': undefined,
    'toLocaleString': undefined,
    'toString': undefined,
    'valueOf': undefined
};

var data = new Data();
data.constructor == undefined;  // Is now true.</pre>
<h2>Discussion</h2>
<p>First, here&#8217;s why I said earlier that the solution appears to be new. <a href="http://www.crockford.com/">Douglas Cockcroft</a>, in his new book <a href="http://http://www.amazon.com/exec/obidos/ASIN/0596517742/wrrrldwideweb">JavaScript: The Good Parts</a>, writes (p23) that there are <em>two solutions to dealing with these undesired properties.</em> The solutions he gives are to use the <em>typeof </em>operator or the <em>hasOwnProperty</em> method. He doesn&#8217;t mention the masking solution above.  Douglas is very knowledgeable about JavaScript, and so that&#8217;s why I think this method is new.  If you know better, please let me know.</p>
<p>Now for an unwelcome but unavoidable side effect.  It your program tries to convert <em>data</em> into a string, it will fail.  This is because <em>data</em> does not have a toString method.  This is the unwelcome side effect.  It is unavoidable, because if <em>data</em> did have a toString method, then it would show up, and <em>data </em>would not be initially empty.  The same goes, of course, for the other Object methods we&#8217;ve masked, such as constructor.</p>
<p>You might think not being able to turn data into a string is a problem.  It shouldn&#8217;t be.  The keys and values of data can still be turned into strings.  If you must turn data into a string, the code</p>
<pre>Object.toString.apply(data)</pre>
<p>will  do this, using the usual method.</p>
<p>Finally, even if your code relies on turning data into a string, you may be better off using the Data approach.  This is because when you add the key &#8216;toString&#8217; to data you&#8217;ll immediately loose the ability to turn data into a string (unless toString has exactly the right value).  If you use the Data approach, your data will start with the Object methods being masked, and so you&#8217;ll have to deal with it up front.  If you use one of the other two approaches, the Object methods will be masked later, when the program is given unusual input.</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/jonathanfine.wordpress.com/16/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/jonathanfine.wordpress.com/16/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/jonathanfine.wordpress.com/16/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/jonathanfine.wordpress.com/16/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/jonathanfine.wordpress.com/16/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/jonathanfine.wordpress.com/16/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/jonathanfine.wordpress.com/16/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/jonathanfine.wordpress.com/16/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/jonathanfine.wordpress.com/16/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/jonathanfine.wordpress.com/16/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=jonathanfine.wordpress.com&blog=1748602&post=16&subd=jonathanfine&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://jonathanfine.wordpress.com/2008/09/20/data-objects-in-javascript/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/242d7f27bd60774efd964dbe680aacda?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">jonathanfine</media:title>
		</media:content>
	</item>
		<item>
		<title>Learning jQuery</title>
		<link>http://jonathanfine.wordpress.com/2008/04/27/learning-jquery/</link>
		<comments>http://jonathanfine.wordpress.com/2008/04/27/learning-jquery/#comments</comments>
		<pubDate>Sun, 27 Apr 2008 22:00:52 +0000</pubDate>
		<dc:creator>jonathanfine</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://jonathanfine.wordpress.com/?p=15</guid>
		<description><![CDATA[Learning from mistakes
This post is about my experience of learning jQuery.  I&#8217;m developing some JavaScript for use with MathTran, and from past experience I know that I need a library.  Elsewhere I explain why I&#8217;ve chosen jQuery. On Friday I started learning jQuery, mostly from the two Packt books, and yesterday and today [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=jonathanfine.wordpress.com&blog=1748602&post=15&subd=jonathanfine&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><h2>Learning from mistakes</h2>
<p>This post is about my experience of learning j<a href="http://jquery.com">Query</a>.  I&#8217;m developing some JavaScript for use with MathTran, and from past experience I know that I need a library.  Elsewhere I explain <a href="http://mathtran.wordpress.com/2008/04/25/gsoc-getting-started/">why I&#8217;ve chosen jQuery</a>. On Friday I started learning jQuery, mostly from the two Packt books, and yesterday and today (Saturday and Sunday) I&#8217;ve started with some coding.</p>
<p>I&#8217;m fairly new to JavaScript programming, and it&#8217;s easy for me to trip up on some of the language features. For example, it&#8217;s my Python habit to write &#8217;self&#8217; when I really should be saying &#8216;this&#8217;. I addition, I&#8217;m not used to the widespread dynamic creation of functions, to be attached to DOM elements to handle events. So in addition to learning how to think jQuery,  I&#8217;ve also been learning how to think JavaScript and DOM.</p>
<p><span id="more-15"></span></p>
<h2>My first mistake: changing the DOM</h2>
<p>Each formula can usefully be displayed in one of three ways</p>
<ul>
<li>TeX notation only</li>
<li>Image only</li>
<li>Both TeX and image</li>
</ul>
<p>I wanted a way to toggle all the math objects between TeX-only and image-only. And I had not even thought that one might want to see <em>both</em> at the same time.</p>
<p>The solution that first came to my mind, and which I started to code, was keep a list of all math-content nodes, and to change each of them in the DOM to achieve the toggle.  In other words, the JavaScript would traverse the math nodes, replacing certain image nodes with TeX notation spans, and vice versa.  And to achieve performance I would keep a list of all math-content nodes.  I even managed to half-persuade myself that this might be a good idea.</p>
<p>Well, I was wrong.  Reading the <em>Learning jQuery book</em>, I came to appreciate the value of  changing the class of an object (such as the document body) in order to change the appearance of the content of the object. So I came to realise that I could keep both the TeX-notation spans <em>and</em> the rendered images in the DOM, and switch the display on and off by changing some classes on the document body (and some fairly trivial CSS also).  From here it&#8217;s pretty easy to see that I could also display both at once if I want to.</p>
<p><strong>Summary</strong> Try to avoid making changes to the DOM.  If something is temporarily not needed, leave it in the DOM, but hide it.  Changing a few classes (which is a small change to the DOM) is better than changing lots of nodes in the DOM. Yes, the work of finding and changing the display of all the mathematics nodes has to be done when the user preference changes, but why not let the browser do that work.  Simply change a class or two and let the browser do the work.</p>
<h2>My second mistake: not being &#8216;HTML creative&#8217;</h2>
<p>One of the things I know I want to do is to transform certain documents.  I wanted the author of the HTML page to supply only the ALT text for certain images, and the JavaScript would provide the  image SRC, which would be a URL pointing to the public MathTran server.</p>
<p>I was thinking of this as being a matter of changing the DOM.  Something like</p>
<ol>
<li>Compute and add a SRC attribute to the image node.</li>
<li>Wrap the node in a span.</li>
<li>Add a child to the span (a sibling of the image) for the TeX source.</li>
<li>Set some classes.</li>
</ol>
<p>I wrote code that did this as a sequence of DOM manipulations. Later, I realised I would need the same code when I was adding completely new mathematical images to  the document.  I&#8217;m also coming round to realising that using the browser to create DOM nodes from a string can be an efficient route, both in terms of programmer effort and browser resources.</p>
<p>So I found myself writing a function that would take a template such as</p>
<pre>
&lt;span class=mathtran&gt;
&lt;span class=mathtran-tex&gt;&lt;/span&gt;
&lt;img class=mathtran-img /&gt;
&lt;/span&gt;
</pre>
<p>and then add the TeX-related objects to the resulting object.  In other words, instead of doing a sequence of DOM manipulations, simply create the DOM node from an HTML template.</p>
<p><strong>Summary </strong>Use HTML as a template when creating DOM nodes, rather than doing everything with DOM manipulators.  Use the manipulators only to change attributes and simple text content.</p>
<h2>My third mistake: being different</h2>
<p>Users of jQuery, after time, build up expectations about how to do things. The library provides standard tools for doing common tasks, and they have a consistent API.  There&#8217;s a jQuery way of doing things, that I am beginning to learn.</p>
<p>With jQuery one writes <code>$('.simple')</code> to select all nodes in the document that have class &#8217;simple&#8217;.  The plugin architecture of jQuery is one of its strengths, and so it makes sens for me to write a MathTran plugin for jQuery. Once one has this, one would expect to write <code>$('.mathtran')</code> to pick up all the MathTran nodes in the document.  In other words, the standard thought patterns of jQuery, which seem to embody a great deal of wisdom and experience of JavaScript manipulation of the DOM, lead one to introduce and use a mathtran class in the CSS.</p>
<p>Put another way, much development follows the route</p>
<ol>
<li>Set up some CSS  (to control the display)</li>
<li>Use some selectors (to find suitable objects in the DOM)</li>
<li>Use jQuery to make minor changes to these objects</li>
</ol>
<p>If I tried to follow this route, then it&#8217;s most likely that I would have avoided mistake one (making large changes in the DOM, rather than using the CSS to leverage some small changes).</p>
<p><strong>Summary</strong> This is not a new mistake.  It is another way of looking at the first mistake. But it points to the benefits of knowing and understanding why things are done and they are in jQuery, and then trying to do the same.</p>
<h2>My first success: the .tex() method</h2>
<p>Every MathTran node — selected by, of course, <code>$('.mathtran') </code>— will contain a TeX string.  It&#8217;s fairly obvious that we want a method to get this string, and another to set it.  Setting it, of course, should change both the content of the span that contains the TeX and also the SRC attribute of the image.</p>
<p>There&#8217;s already a similar method in jQuery, which is the <code>html() method. You can read documentation for it <a href="http://docs.jquery.com/Attributes/html">here</a></code>. Giving the  <code>tex() </code>method a similar API makes life so much easier, both for the programmer of the MathTran plugin for jQuery and for the user.</p>
<h2>My second success: the .mathtran() method</h2>
<p>If only out of vanity, we&#8217;d like the mathtran plugin to provide a <code>mathtran() </code>method.  It&#8217;s fairly clear that it should construct mathtran nodes, that can be placed in the document tree.  A little thought tells us that is should be what in some languages is called a class method.  Mathematics exists in two forms, inline and display.  The typography is different in the two cases.  For example, compare <img style="vertical-align:middle;" src="http://www.mathtran.org/cgi-bin/mathtran?D=2;tex=%5Csum_%7Bk%3D1%7D%5En%20k" alt="" /> with <img style="vertical-align:middle;" src="http://www.mathtran.org/cgi-bin/mathtran?D=1;D=2;tex=%5Cdisplaystyle%5Csum_%7Bk%3D1%7D%5En%20k" alt="" width="42" height="53" />. The first is good for paragraph text (where it is important that formulas not be too high) and the second works well in displays (which is used for important formulas, and where the width should not be too great).  So it&#8217;s clear that the typographic style should be a parameter to the <code>mathtran() method.</code></p>
<p>I&#8217;ve not sorted out the API for this method yet, but it&#8217;s beginning to take shape.</p>
<h2>How to &#8216;toggle&#8217; with three choices</h2>
<p>This post started with the three ways of displaying mathematics — TeX notation only, image only, or both.  I&#8217;d like to put a button on the page that &#8216;toggles&#8217; between the three possibilities.  Writing this in a way that works well with jQuery is my current challenge, and part of my JavaScript, DOM and jQuery learning curve.  You can see my currrent attempt <a href="http://code.google.com/p/mathtran-javascript/source/browse/trunk/jfine/jquery.mathtran.js?r=30">here</a>.</p>
<h2>Conclusion</h2>
<p>It&#8217;s important to make mistakes, and it&#8217;s important to learn from them.  This is an example of the dialog between theory and practice (and my habit is to favour theory).  As for jQuery, it has a well thought out API (that&#8217;s theory) which I should use as templates and examples when coding the MathTran plugin for jQuery.  I should learn to rely more on CSS, particuarly when it can leverage minor changes to the DOM.</p>
<p>One final point.  I&#8217;ve found that jQuery favours a sort of declarative approach to programming (make a series of statements about the situation and leave the browser to follow the resulting rules) rather than the procedural approach (tell the browser, step by step) what it should do.  This is another aspect of the CSS example I&#8217;ve discussed in this post.</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/jonathanfine.wordpress.com/15/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/jonathanfine.wordpress.com/15/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/jonathanfine.wordpress.com/15/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/jonathanfine.wordpress.com/15/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/jonathanfine.wordpress.com/15/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/jonathanfine.wordpress.com/15/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/jonathanfine.wordpress.com/15/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/jonathanfine.wordpress.com/15/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/jonathanfine.wordpress.com/15/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/jonathanfine.wordpress.com/15/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/jonathanfine.wordpress.com/15/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/jonathanfine.wordpress.com/15/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=jonathanfine.wordpress.com&blog=1748602&post=15&subd=jonathanfine&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://jonathanfine.wordpress.com/2008/04/27/learning-jquery/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/242d7f27bd60774efd964dbe680aacda?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">jonathanfine</media:title>
		</media:content>

		<media:content url="http://www.mathtran.org/cgi-bin/mathtran?D=2;tex=%5Csum_%7Bk%3D1%7D%5En%20k" medium="image" />

		<media:content url="http://www.mathtran.org/cgi-bin/mathtran?D=1;D=2;tex=%5Cdisplaystyle%5Csum_%7Bk%3D1%7D%5En%20k" medium="image" />
	</item>
		<item>
		<title>Using MathTran in blogs and wikis</title>
		<link>http://jonathanfine.wordpress.com/2008/02/27/using-mathtran-in-blogs-and-wikis/</link>
		<comments>http://jonathanfine.wordpress.com/2008/02/27/using-mathtran-in-blogs-and-wikis/#comments</comments>
		<pubDate>Wed, 27 Feb 2008 14:36:58 +0000</pubDate>
		<dc:creator>jonathanfine</dc:creator>
				<category><![CDATA[mathtran]]></category>

		<guid isPermaLink="false">http://jonathanfine.wordpress.com/?p=13</guid>
		<description><![CDATA[This post is mainly for system administrators and developers who want to add mathematics capabilities to a blog or wiki that they host or develop.  We hope that in a year or so some of the ideas we describe here will be available to ordinary users who have a blog, say on WordPress.
After an [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=jonathanfine.wordpress.com&blog=1748602&post=13&subd=jonathanfine&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>This post is mainly for system administrators and developers who want to add mathematics capabilities to a blog or wiki that they host or develop.  We hope that in a year or so some of the ideas we describe here will be available to ordinary users who have a blog, say on WordPress.</p>
<p>After an Introduction, we discuss Light-, Medium- and Heavy- weight installation of MathTran.  Then we discuss how to print mathematics using MathTran. Finally, we revisit the examples in the introduction, and state conclusions.</p>
<p><span id="more-13"></span></p>
<h2>Introduction</h2>
<p>In fact, let&#8217;s start with <a href="http://terrytao.wordpress.com">Terry Tao&#8217;s blog</a>, which is on WordPress.   In case you didn&#8217;t know, <a href="http://en.wikipedia.org/wiki/Terence_Tao">Terry Tao</a> is an eminent and talented young mathematician who is extremely web-savvy.  He decided to move from a static web-site to a blog for his news and discussion articles about a year ago.  Original he moved to blogspot, but then soon moved on to <a href="http://www.wordpress.com">WordPress</a>, because it gave better <a href="http://en.wikipedia.org/wiki/LaTeX">LaTeX</a> support.  Last month he told us that he has decided to <a href="http://terrytao.wordpress.com/2008/01/25/book-version-of-the-blog/">publish a book version of his blog</a>.</p>
<p>For me, Terry Tao&#8217;s blog provides a good example of where we are right now, and where we&#8217;d like to be.  Of course, there are other examples.  Most of us are not nearly as mathematical as Tao is.  The many mathematics pages on <a href="http://en.wikipedia.org/">Wikipedia</a> provide another example.  The Wikimedia foundation has recently announced a project to <a href="http://wikimediafoundation.org/wiki/Wikis_Go_Printable">convert Wikipedia content to PDF</a>.  (The development of the software is being led by <a href="http://pediapress.com/">PediaPress.com</a>, whose web-site is one of the <a href="http://djangobook.com/en/1.0/appendixA/">case studies</a> in The Django Book, which neatly ties in with another interest of mine.)</p>
<p>So this may be enough to set the stage.  We&#8217;re interested in getting mathematics on blog, wikis, forums and other &#8216;Web2.0&#8242; sites.  We want good LaTeX support, good display, and the ability to go to PDF.</p>
<h2>Lightweight installation</h2>
<p><a href="http://www.mathtran.org/">MathTran</a> is a public web service, and so a lightweight installation can be made simple by putting some Javascript in the HTML header, and coding up the IMG elements on the page appropriately.  All this is described on the MathTran home page (at present, it might get moved later).</p>
<p>Another intriguing form of installation is via a <a href="http://www.mathtran.org/wiki/index.php/MathTran_bookmarklet">MathTran bookmarklet</a>, which has been devised by my colleague Tim Hunt at The Open University.  This allows MathTran to do it&#8217;s magic on content that has been marked up using TeX&#8217;s traditional $$ x^2+y^2=1$$ notation. This is a transformation controlled by the web-browser and its user.  It does not require the server of the web page to do anything at all.  To try it, install this bookmarklet in the way Tim described above and click on it.  You will see the previous formula be replaced by it&#8217;s rendered TeX form.  (The MathTran client <a href="http://www.humanized.com/enso/beta/ensotexanywhere">Enso TeX Anywhere</a>  does something similar in many Windows documents.)</p>
<p>MathTran can provide lightweight installation because</p>
<ul>
<li>It is a high-performance web service (it runs TeX as a daemon, waiting and ready for the next request)</li>
<li>It is a public web service</li>
<li>It can provide its service via dynamic HTML</li>
</ul>
<p>Any public high-performance dynamic HTML web service will support lightweight installation.  One of the most widely deployed examples is the <a href="http://www.google.com/adsense/">Google Ad Client</a>, which adds advertising to many web pages (and provides revenue to the owner of the page).</p>
<h2>Medium-weight installation</h2>
<p>Now suppose you don&#8217;t want your users to get the mathematical images from the public MathTran server.  Several good (and perhaps not so good) reasons for this are</p>
<ul>
<li>You don&#8217;t want to rely on a third party service.</li>
<li>Your users are in a secure or mobile environment, and do not have direct contact with the Internet.</li>
<li>You want goodies, such as baseline alignment of images, that at present require the page and the image to come from the same server.</li>
<li>You want to write code that works as if you had your own MathTran server.</li>
<li>You want a backup in case your own MathTran server (see below) goes down.</li>
<li>You don&#8217;t want your users to know you&#8217;re using MathTran.</li>
</ul>
<p>You can get most or all of this by setting up a <a href="http://en.wikipedia.org/wiki/Proxy_server#Transparent_and_non-transparent_proxy_server">transparent proxy server</a>, complete with caching if you need it.  None of this should be at all hard for a web-developer, and if you need and write one please do let us know so we can share it.  Who knows, perhaps there&#8217;s one out there already.</p>
<p>[Some clever Javascript programming, together with serving <a href="http://en.wikipedia.org/wiki/JSON">JSON</a>,  allows baseline alignment even when the images come from somewhere else.  But for now I encourage you to set up a transparent proxy if you can.]</p>
<h2>Heavy-weight installation</h2>
<p>This will be, as the name suggests, more work.  For a start, you will need Linux or Unix because the MathTran server uses named pipes and sockets in a way that Windows does not support.  I hope to discuss this further in another post.</p>
<h2>Printing mathematics</h2>
<p>Let&#8217;s suppose you want to produce a high-quality PDF file from a web page that contains MathTran mathematics (or at least mathematics that MathTran can handle).</p>
<p>Well, you&#8217;ll need something to handle the ordinary text, and if that something is TeX then you can probably just feed the TeX-encoded mathematics into it.  But suppose your using some other tool, such as <a href="http://xmlgraphics.apache.org/fop/">Apache&#8217;s FOP</a>.  MathTran generates bitmaps, so then can be included into the output by FOP.  But we want <i>high-quality</i> output, and that means using outline fonts.</p>
<p>Each bitmap image served by MathTran contain invisible metadata, including the <a href="http://en.wikipedia.org/wiki/Device_independent_file_format">dvi output</a> from TeX specific to that image.  This dvi output, when combined with a suitable header, can be processed by <a href="http://www.tug.org/texinfohtml/dvips.html">dvips</a> to produce EPS files, which FOP knows how to handle.  An alternative route, which is more work but which probably produce better results, is to teach the PDF-writer used by FOP how to translate the dvi output into PDF directly.</p>
<p>Compared to writing a high-quality typesetting program such as TeX, writing software that translates TeX output to EPS or PDF or whatever is fairly simple (or so I believe, not having written either).  Integrating MathTran into an open source PDF formatting program should not be so difficult, and would certainly be easier than writing an alternative to TeX.</p>
<p>Here is an example.  After the EuroPython 2007 conference Dinu Gherman created a simple test script (lightweight application) that shows how to use MathTran with <a href="http://www.reportlab.com/">ReportLab</a> (which has an <a href="http://www.reportlab.org/">open source version</a>).</p>
<h2>Conclusions</h2>
<p>Both WordPress and Wikipedia use (La)TeX as their input syntax, and use TeX typesetting to generate mathematical images.  TeX is the mathematics notation used by research mathematicians and physicists.  MathTran makes TeX typesetting available as a public web service, which allows for lightweight installation in third party applications.</p>
<p>The present situation is not satisfactory &#8211; Terry Tao has to do manual conversion work to turn his blog into a book, and I expect that PediaPress will have to work hard to get mathematics working in their output.  However, I hope that I have shown how MathTran both improves things where we are and is part of the path that takes us to where we want to be.</p>
<p>[Clearly, there's more to say than we've said here.  Please leave comments and I'll write another post.]</p>
<h2>Postscript</h2>
<h3>A Java client &#8211; 27 Feb 2008</h3>
<p>Alex Clk has written a <a href="http://groovy-news.org/e/page/axelclk?entry=get_latex_formula_image_from">simple MathTran client in Java</a>. To answer a couple of questions he asks in that post,</p>
<ul>
<li>To change the size of the image, use D=&lt;n&gt; in the query string, where &lt;n&gt; ranges from 1 to 10.</li>
<li>The MathTran service has funding to August 2008, and  is I expect that funding for 2009 will also be found.</li>
</ul>
<p>Of course, the more useful and used it is, the easier it is to find funds.</p>
<h3>IE has a bookmarklet length limit &#8211; 4 Mar 2008</h3>
<p>Internet Explorer has a length limit on bookmarklets,  and Tim Hunt&#8217;s MathTran bookmarklet exceeds it.  With rewriting it can be cut down to fit, but I&#8217;ve not done that yet.  For more details see Browser Bugs on <a href="https://www.squarefree.com/bookmarklets/browsers.html">this page</a>.</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/jonathanfine.wordpress.com/13/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/jonathanfine.wordpress.com/13/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/jonathanfine.wordpress.com/13/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/jonathanfine.wordpress.com/13/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/jonathanfine.wordpress.com/13/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/jonathanfine.wordpress.com/13/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/jonathanfine.wordpress.com/13/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/jonathanfine.wordpress.com/13/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/jonathanfine.wordpress.com/13/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/jonathanfine.wordpress.com/13/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/jonathanfine.wordpress.com/13/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/jonathanfine.wordpress.com/13/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=jonathanfine.wordpress.com&blog=1748602&post=13&subd=jonathanfine&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://jonathanfine.wordpress.com/2008/02/27/using-mathtran-in-blogs-and-wikis/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/242d7f27bd60774efd964dbe680aacda?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">jonathanfine</media:title>
		</media:content>
	</item>
		<item>
		<title>Microsoft loves Yahoo &#8230;</title>
		<link>http://jonathanfine.wordpress.com/2008/02/09/microsoft-and-yahoo/</link>
		<comments>http://jonathanfine.wordpress.com/2008/02/09/microsoft-and-yahoo/#comments</comments>
		<pubDate>Sat, 09 Feb 2008 20:53:24 +0000</pubDate>
		<dc:creator>jonathanfine</dc:creator>
				<category><![CDATA[humour]]></category>

		<guid isPermaLink="false">http://jonathanfine.wordpress.com/?p=12</guid>
		<description><![CDATA[&#8230; but will they be happy together?
Microsoft loves Yahoo, but will they be happy together?  To find out visit the LoveGraph page for this match.
LoveGraph uses a special algorithm to generate data about the potential of the match, which it then graphs. Do pay particular attention to the &#8220;Spheres of Interest Overlap&#8221; chart.
LoveGraph uses [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=jonathanfine.wordpress.com&blog=1748602&post=12&subd=jonathanfine&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><h2>&#8230; but will they be happy together?</h2>
<p>Microsoft loves Yahoo, but will they be happy together?  To find out visit <a href="http://lovegraph.thefootnotes.net/results.html?YourName=Microsoft&amp;TheirName=Yahoo">the LoveGraph page for this match</a>.</p>
<p>LoveGraph uses a special algorithm to generate data about the potential of the match, which it then graphs. Do pay particular attention to the &#8220;Spheres of Interest Overlap&#8221; chart.</p>
<p>LoveGraph uses charts and graphs generated by <a href="http://code.google.com/apis/chart/">Google Charts</a>.</p>
<p><span id="more-12"></span></p>
<h2>Some comparisons</h2>
<p>Here are some more serious comments on Google and Microsoft, based on looking at a couple of web pages.</p>
<p>Google sell advertising on its search pages.  It also sell advertising on other people&#8217;s pages.  For example, the <a href="http://lovegraph.thefootnotes.net/results.html?YourName=Microsoft&amp;TheirName=Yahoo">LoveGraph</a> page mentioned above contains advertisements from Google.  Both Google and the owners of LoveGraph get revenue if these advertisements are followed.</p>
<p>I&#8217;ve taken a brief usability look at the <a href="http://www.microsoft.com">Microsoft home page</a>.  The graphic design is very impressive.  At the top right there is a search gadget.  Under the search box is a black down triangle next to the words &#8216;All Microsoft sites&#8217;.  Do not press this triangle.</p>
<p>Oh, you did press it.  You found that it &#8216;lifts up&#8217; the menu, quite slowly.  I timed it as 7 seconds.  I don&#8217;t see the point of it, and it&#8217;s prominently on the home page.  If you have lifted it up, do drop it down (another 7 seconds).  Now press the &#8216;All Products&#8217; link.</p>
<p>This brings up a screen-full of product images.  Click on one of them, and then press the browser&#8217;s back button.  And it does take you back, but to the Microsoft home page, not to the &#8216;All Products&#8217; images you were previously at.</p>
<p>It is possible that Microsoft taking over Yahoo! will result in Yahoo being more of a rival to Google.  But is also seems that the opposite is also quite possible.</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/jonathanfine.wordpress.com/12/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/jonathanfine.wordpress.com/12/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/jonathanfine.wordpress.com/12/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/jonathanfine.wordpress.com/12/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/jonathanfine.wordpress.com/12/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/jonathanfine.wordpress.com/12/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/jonathanfine.wordpress.com/12/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/jonathanfine.wordpress.com/12/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/jonathanfine.wordpress.com/12/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/jonathanfine.wordpress.com/12/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/jonathanfine.wordpress.com/12/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/jonathanfine.wordpress.com/12/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=jonathanfine.wordpress.com&blog=1748602&post=12&subd=jonathanfine&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://jonathanfine.wordpress.com/2008/02/09/microsoft-and-yahoo/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/242d7f27bd60774efd964dbe680aacda?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">jonathanfine</media:title>
		</media:content>
	</item>
		<item>
		<title>Django and the MathTran website &#8211; AJAX and templates</title>
		<link>http://jonathanfine.wordpress.com/2008/02/02/django-and-the-mathtran-website-part-2/</link>
		<comments>http://jonathanfine.wordpress.com/2008/02/02/django-and-the-mathtran-website-part-2/#comments</comments>
		<pubDate>Sat, 02 Feb 2008 08:43:17 +0000</pubDate>
		<dc:creator>jonathanfine</dc:creator>
				<category><![CDATA[django]]></category>
		<category><![CDATA[mathtran]]></category>

		<guid isPermaLink="false">http://jonathanfine.wordpress.com/?p=11</guid>
		<description><![CDATA[Introduction
In my previous post I spoke about ReST.  It&#8217;s not able to do what I want, which is a nuisance.  But most of the post of about coding forms such as that on the MathTran home page using Django templates.  In the course of the post I come to the conclusion that [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=jonathanfine.wordpress.com&blog=1748602&post=11&subd=jonathanfine&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><h2>Introduction</h2>
<p>In my <a href="http://jonathanfine.wordpress.com/2008/01/26/django-and-the-mathtran-website-part-1/">previous post</a> I spoke about <a href="http://en.wikipedia.org/wiki/ReStructuredText">ReST</a>.  It&#8217;s not able to do what I want, which is a nuisance.  But most of the post of about coding forms such as that on the <a href="http://www.mathtran.org">MathTran home page</a> using Django templates.  In the course of the post I come to the conclusion that providing such forms is a matter just for the template, and has nothing much to do with the view!  Finally, I make some remarks about AJAX, which is used (along with some rather improper dynamic HTML) in the present implementation.</p>
<p><span id="more-11"></span></p>
<h2>Some problems with ReST</h2>
<p>I&#8217;m now using ReST to author content for the website, and I&#8217;m finding it awkward.  I quite like to put a link to be followed at the end of a sentence.  Something like:  Instructions on how to do learn TeX are <a href="http://www.mathtran.org/tex">here</a>.  (This link is broken at the time of writing.)  However, ReST does not allow me to use &#8216;here&#8217; twice in the same page, but pointing to different web pages.  I find that this cramps my style, and in time there will be an example <a href="http://www.mathtran.org">here</a>.</p>
<p>Here&#8217;s another problem.  The new home page will have a two-column layout, with main content on the left, and news on the right.  I will, of course, use CSS to do the styling.  And so I have to create two content DIV&#8217;s in the body.  I can do this with ReST by having separate pages for the main content and the news, and this might be the best thing to do, but I don&#8217;t want to be forced into doing that by the architecture of ReST.</p>
<p>Finally, on the <a href="http://www.mathtran.org">MathTran home page</a> there is a form, that allows users to experiment with TeX.  I don&#8217;t want to hardcode this form into the ReST source for the home page, and in fact I can&#8217;t, because I&#8217;ll need Django to put some results in under the form.  And so it looks as if I&#8217;ll be forced into some appalling hack, such as putting a special string such as <code>{{ my_form }}</code> in the ReST source, which Django can then replace by the form.  In short, a tiny templating language, processing the output of ReST.</p>
<p>I decided to switch from authoring in HTML because it is more work than it should be.  But it seems that ReST can also produce additional work.</p>
<h2>CSS and ReST</h2>
<p>I&#8217;m going to use the CSS <code>float: right</code> style to get the two-column layout, and that requires the sidebar DIV to appear <i>before</i> the content DIV in the HTML.  This <i>might</i> be a design fault in HTML/CSS, but I don&#8217;t think so.  In any case, this is another example of how ReST is not fitting in well with other parts of the system.  In my <a href="http://jonathanfine.wordpress.com/2008/01/26/django-and-the-mathtran-website-part-1/">previous post</a> I explained how I was having to do a hack to get the title to come out right.  That said, I&#8217;m pleased that I&#8217;m using CSS, and seem to be getting to grips with the separation of content and style. I&#8217;m using Simon Collison&#8217;s <a href="http://www.apress.com/book/view/1590596897">beginner&#8217;s book</a> as a reference.</p>
<h2> The TeX data entry form</h2>
<p>The present and new MathTran home pages will have a TeX data entry form, that allows the user to experiment with MathTran.  This form, perhaps with variation, will be used elsewhere on the new site. It is an important component, and it&#8217;s implementation will make more use of  the framework Django provides.</p>
<p>On the current site the form was written using JavaScript plus dynamic HTML, and prior to that we used a CGI script.  The nice thing about the JavaScript approach, besides the nice user interface is provided, is that it allowed the form to be reused across the site without copying large chunks of code.</p>
<p>But some users might not be able to use JavaScript, or might for good reasons prefer not to use it. I&#8217;m beginning to value more the approach, that the site should be made accessible first, and then JavaScript can be used to enhance functionality.  Not using JavaScript makes the site easier to test. And now that I&#8217;m using Django with its template language, the form should be easy to reuse.</p>
<p>The challenge here is to refactor the existing functionality so that business logic belongs to the view, presentation belongs to the template, style belongs to the CSS style sheet, and there are sufficient hooks to allow JavaScript and dynamic HTML to replace the logic in the view.</p>
<h2>Ajax and Django forms</h2>
<p>It&#8217;s now Sunday 3rd February, and I&#8217;m going to summarise the progress I&#8217;ve made. First, and this is important, I now understand the problem.  It is this.  In the current MathTran website pages some pages contain &#8216;user feedback&#8217; data entry forms, that are created using JavaScript and function using some Ajax (to get the TeX log and the depth of the image).  I don&#8217;t want to rely on JavaScript in this way, because it is repeating all the problems of Dynamic HTML of a few years back, as described in <a href="http://www.beginningjavascript.com/">Chris Heilmann&#8217;s book</a>, which I am using as guidance for good practice.  I would like to provide the existing functionality on the new site without using JavaScript, and to enhance the interface by using JavaScript, if JavaScript is available.</p>
<p>So that is is the description of the problem.  A bit of thinking tells us why that is a problem.  Django has a View + Template architecture (the Model is not used here).  But the DHTML approach so to speak promotes ordinary markup into interactive elements.  And so to achieve similar functionality <i>for the author of the web page or Django template </i>the View is not involved either.  These forms provide what I have called <i>user feedback</i> or more specifically the opportunity to experiment with TeX and some examples.  They are a matter for the author of the template/page, not the programmer of the view.  In particular, they should be available on any template, just as H1 headings are available on a view.</p>
<p>This brings me to the thing I liked about the DHMTL approach I followed, which is that the page author supplies minimal markup, and &#8216;the system&#8217; provides the rest.  The page author does not have to copy-and-paste boilerplate code.  This is good, but using client-side JavaScript as the system that provides the rest is not a good idea.  Except it&#8217;s not clear that for ordinary users (as opposed to power users such as Djangonauts) there is an alternative to coding in ordinary HTML.</p>
<p>I explored the problem without properly understanding it (and with gaps in my Django knowledge), and this turned out to be a good thing to do.  First of all, I coded one of these forms using the View-Template architecture.  I then realised that the Template shouldn&#8217;t really be tied to the view in this way.  This was particularly acute when there were to be two, three or more of these forms on a template.</p>
<h2>Using a working example</h2>
<p>At this point I had a working example, so I knew it could be done.  Also, the example provided a helpful framework for further exploration.  So the thing to do was to do everything in the Template.  (I could have deduced this from an abstract analysis of the problem, but it was good to get the experience into my coding fingers, and to have a working example.)  So now I was casting about, without any other route, for a way to do the form using the Template only.</p>
<p>At this point I recalled that a well-written template does not change any data.  This is part of the design philosophy of Django templates.  In <a href="http://www.djangobook.com/en/1.0/chapter04/">Chapter 4 of The Django Book</a> we read <i>A template cannot set a variable or change the value of a variable </i>and that custom template tags can be written that do allow this.  So that is what I was forced into doing, by the in my view quite reasonable requirements.  By the way, being trained as a mathematician, I&#8217;m quite fond of problems that have exactly one solution.  In mathematics it&#8217;s often easier to find something, if you know there is only one of them to be found.  So here I actually liked the way the logic of the situation forced me into a particular solution, and I also liked the solution that so appeared.</p>
<p>So I sat down, motivated, to write a custom template tag that did what I want, and I had something working by the end of the day.  It&#8217;s not ready to post anywhere yet, but I can show you how a preliminary form of the template interface.</p>
<blockquote>
<pre>&lt;form&gt;
{% mathtran wobble %}{# Assigns a value to the variable wobble #}
&lt;p&gt;TeX input: {{wobble.elt}}&lt;/p&gt;
&lt;input type="text" name="wobble" size="50" value="{{wobble.value}}"/&gt;
&lt;input type="hidden" name="old_wobble" value="{{wobble.old_value}}"/&gt;
&lt;input type="submit" name="set_wobble" value="Try it"/&gt;
&lt;p&gt;TeX output: {{wobble.img}}&lt;/p&gt;
&lt;p&gt;TeX errors: {{wobble.log}}&lt;/p&gt;</pre>
</blockquote>
<p>This, of course, contains a large amount of boilerplate code that should be incorporated into the behaviour and properties of the mathtran tag.</p>
<h2>Conclusion</h2>
<p>Coding these forms properly is more work that I thought at first, particularly if I&#8217;m to do it properly. But the payoff is likely to be code that can be reused by any Django site that wants to use the MathTran service.  Finally, there is a <a href="http://code.djangoproject.com/wiki/AJAX">Django wiki page on AJAX</a>  which has some useful links.</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/jonathanfine.wordpress.com/11/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/jonathanfine.wordpress.com/11/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/jonathanfine.wordpress.com/11/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/jonathanfine.wordpress.com/11/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/jonathanfine.wordpress.com/11/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/jonathanfine.wordpress.com/11/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/jonathanfine.wordpress.com/11/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/jonathanfine.wordpress.com/11/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/jonathanfine.wordpress.com/11/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/jonathanfine.wordpress.com/11/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/jonathanfine.wordpress.com/11/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/jonathanfine.wordpress.com/11/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=jonathanfine.wordpress.com&blog=1748602&post=11&subd=jonathanfine&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://jonathanfine.wordpress.com/2008/02/02/django-and-the-mathtran-website-part-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/242d7f27bd60774efd964dbe680aacda?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">jonathanfine</media:title>
		</media:content>
	</item>
	</channel>
</rss>