<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Blog 4 &#187; Javascript</title>
	<atom:link href="http://nickzarr.com/blog4/category/programming-2/javascript/feed/" rel="self" type="application/rss+xml" />
	<link>http://nickzarr.com/blog4</link>
	<description>Chosen by fair dice roll. Guaranteed random.</description>
	<lastBuildDate>Sun, 22 Apr 2012 18:29:09 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Jumping into Javascript &#8211; Good news and bad news</title>
		<link>http://nickzarr.com/blog4/2011/11/jumping-into-javascript-good-news-and-bad-news/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=jumping-into-javascript-good-news-and-bad-news</link>
		<comments>http://nickzarr.com/blog4/2011/11/jumping-into-javascript-good-news-and-bad-news/#comments</comments>
		<pubDate>Mon, 14 Nov 2011 12:54:31 +0000</pubDate>
		<dc:creator>Nick Zarczynski</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[jamochatrade]]></category>
		<category><![CDATA[jumping into javascript]]></category>

		<guid isPermaLink="false">http://nickzarr.com/blog4/?p=1737</guid>
		<description><![CDATA[I have resumed development of the JamochaTrade project and there has been a lot of progress over the last week or so. The last article left off with a very rudimentary candlestick chart that got its data via cross-domain JSON. I am pleased to announce that a UI has been added, along with the ability [...]]]></description>
			<content:encoded><![CDATA[<p>I have resumed development of the JamochaTrade project and there has been a lot of progress over the last week or so.  The last article left off with a very rudimentary candlestick chart that got its data via cross-domain JSON.  I am pleased to announce that a UI has been added, along with the ability to buy and sell stocks, limit and stop orders, 5 different chart types (candlestick, bar, ohlc, hlc and line), a portfolio view, pending orders view, advancing time by week/month is animated as well as a host of other improvements.</p>
<p>Unfortunately the speed at which these features have been added has ended the step-by-step nature of this series.  I will continue to provide progress updates and hope to produce a number of articles based on architecture or challenges that arise during development.  Though there is not much discussion, you can still <a href="https://github.com/jacktrades/JamochaTrade/commits/master">follow along with the commit log</a> of the project.  Each commit is relatively small and, in most cases, addresses a single concern.  There is also some information provided in the <a href="https://github.com/jacktrades/JamochaTrade/issues">issue tracker</a>, which I have been making heavy use of and almost every commit has an associated issue.</p>
<p>The project is not yet ready for release, however there is a <a href="http://nickzarr.com/demos/jamochatrade/">preview version available</a>.  Criticisms, comments, bug reports and feature requests are more than welcome.  You can leave comments below or file a bug report or feature request on the <a href="https://github.com/jacktrades/JamochaTrade/issues">issue tracker</a>.</p>
<h3><a href="http://nickzarr.com/demos/jamochatrade/" title="JamochaTrade">Try the demo</a></h3>
<p>&nbsp;</p>
<p><strong>Features:</strong></p>
<ul>
<li>5 chart types (candlestick, bar, ohlc, hlc, line)</li>
<li>15, 30, 60 and 90 day charts</li>
<li>Change chart colors</li>
<li>Advance time by day, week or month (animated)</li>
<li>Buy/sell stocks</li>
<li>Portfolio view</li>
<li>Sell directly from portfolio view</li>
<li>Market, limit and stop orders</li>
<li>Pending order pane</li>
<li>Cancel pending orders</li>
<li>Change theme of site</li>
<li>Previously viewed stock data is cached for fast switching</li>
<li>Most features auto-hide when not necessary to reduce clutter</li>
<li>Account balance and total portfolio value show gains/losses</li>
</ul>
<p><a href="http://nickzarr.com/demos/jamochatrade/"><img src="http://nickzarr.com/blog4/wp-content/uploads/2011/11/jt01-e1321274006867.png" alt="Screenshot 1" /></a></p>
<p><a href="http://nickzarr.com/demos/jamochatrade/"><img src="http://nickzarr.com/blog4/wp-content/uploads/2011/11/jt02-e1321274476128.png" alt="Screenshot 2" /></a></p>
<p><a href="http://nickzarr.com/demos/jamochatrade/"><img src="http://nickzarr.com/blog4/wp-content/uploads/2011/11/jt03-e1321274459766.png" alt="Screenshot 3" /></a></p>
<p><a href="http://nickzarr.com/demos/jamochatrade/"><img src="http://nickzarr.com/blog4/wp-content/uploads/2011/11/jt04-e1321274438189.png" alt="Screenshot 4" /></a></p>
<p><a href="http://nickzarr.com/demos/jamochatrade/"><img src="http://nickzarr.com/blog4/wp-content/uploads/2011/11/jt05-e1321274136418.png" alt="Screenshot 5" /></a></p>
<p><a href="http://nickzarr.com/demos/jamochatrade/"><img src="http://nickzarr.com/blog4/wp-content/uploads/2011/11/jt06-e1321274036579.png" alt="Screenshot 6" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://nickzarr.com/blog4/2011/11/jumping-into-javascript-good-news-and-bad-news/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Javascript wisdom from the jQuery source code</title>
		<link>http://nickzarr.com/blog4/2011/11/javascript-wisdom-from-the-jquery-source-code/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=javascript-wisdom-from-the-jquery-source-code</link>
		<comments>http://nickzarr.com/blog4/2011/11/javascript-wisdom-from-the-jquery-source-code/#comments</comments>
		<pubDate>Mon, 14 Nov 2011 11:44:45 +0000</pubDate>
		<dc:creator>Nick Zarczynski</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[jquery]]></category>

		<guid isPermaLink="false">http://nickzarr.com/blog4/?p=1724</guid>
		<description><![CDATA[Here are a few things I learned from reading the jQuery source code. I&#8217;m documenting them here because they&#8217;re edge cases that are, in some cases, difficult to reproduce and debug. The jQuery source code is very clean and well commented and has many more gems than what is listed here. &#160; getElementById sometimes returns [...]]]></description>
			<content:encoded><![CDATA[<p>Here are a few things I learned from reading the <a href="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js">jQuery source code</a>.  I&#8217;m documenting them here because they&#8217;re edge cases that are, in some cases, difficult to reproduce and debug.  The jQuery source code is very clean and well commented and has many more gems than what is listed here.</p>
<p>&nbsp;</p>
<h3>getElementById sometimes returns elements by name in some versions of IE and Opera.</h3>
<pre class="brush: jscript; title: ; notranslate">
                                // HANDLE: $(&quot;#id&quot;)
                                } else {
                                        elem = document.getElementById( match[2] );

                                        // Check parentNode to catch when Blackberry 4.6 returns
                                        // nodes that are no longer in the document #6963
                                        if ( elem &amp;&amp; elem.parentNode ) {
                                                // Handle the case where IE and Opera return items
                                                // by name instead of ID
                                                if ( elem.id !== match[2] ) {
                                                        return rootjQuery.find( selector );
                                                }

                                                // Otherwise, we inject the element directly into the jQuery object
                                                this.length = 1;
                                                this[0] = elem;
                                        }

                                        this.context = document;
                                        this.selector = selector;
                                        return this;
                                }
</pre>
<p>Even something as simple as getElementById can have edge cases you have to take into account.  In IE 6 and 7 for Windows and some versions of Opera, dom elements can be returned by name instead of id.  In addition, as seen in the comments of the code above, Blackberry 4.6 can return nodes that are not even in the document.</p>
<p>See references <a href="http://remysharp.com/2007/02/10/ie-7-breaks-getelementbyid/">here</a> and <a href="http://www.456bereastreet.com/archive/200802/beware_of_id_and_name_attribute_mixups_when_using_getelementbyid_in_internet_explorer/">here</a>.</p>
<p>&nbsp;</p>
<h3>A false positive on the domready event can cause rapid page refreshing.</h3>
<pre class="brush: jscript; title: ; notranslate">
        // Handle when the DOM is ready
        ready: function( wait ) {
                // Either a released hold or an DOMready/load event and not yet ready
                if ( (wait === true &amp;&amp; !--jQuery.readyWait) || (wait !== true &amp;&amp; !jQuery.isReady) ) {
                        // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
                        if ( !document.body ) {
                                return setTimeout( jQuery.ready, 1 );
                        }
</pre>
<p>The domready event, which is present in some form or another in many browsers can fire before the dom is actually loaded.  This can cause continuous page reloads and other errors which are hard to reproduce and debug.  The solution to this is to check that the document.body is not null before accepting the domready event.</p>
<p>Of course you can always fall back to the window.onload event, however this will force you to wait until the entire content of the page (including possibly large images) has loaded.</p>
<p>See references <a href="http://bugs.jquery.com/ticket/5443">here</a> and <a href="http://www.sigsiu.net/forum/community-board-for-troubleshooting-problems/internet-explorer-dom-readiness-problem-and-solution-explained/">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://nickzarr.com/blog4/2011/11/javascript-wisdom-from-the-jquery-source-code/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Classes and Instances in Javascript Using the Closure Method</title>
		<link>http://nickzarr.com/blog4/2011/07/classes-and-instances-in-javascript-using-the-closure-method/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=classes-and-instances-in-javascript-using-the-closure-method</link>
		<comments>http://nickzarr.com/blog4/2011/07/classes-and-instances-in-javascript-using-the-closure-method/#comments</comments>
		<pubDate>Thu, 28 Jul 2011 13:15:07 +0000</pubDate>
		<dc:creator>Nick Zarczynski</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[class]]></category>
		<category><![CDATA[closure]]></category>
		<category><![CDATA[inheritance]]></category>
		<category><![CDATA[object]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://nickzarr.com/blog4/?p=1236</guid>
		<description><![CDATA[I was reading a question about what every Javascript programmer should know on StackOverflow and found this useful pattern for using the more classic class/instance pattern instead of Javascript&#8217;s standard prototype method. I found the last example to be quite elegant and want to preserve it here for reference. With this pattern you have to [...]]]></description>
			<content:encoded><![CDATA[<p>I was reading a question about <a href="http://stackoverflow.com/questions/2628672/what-should-every-javascript-programmer-know/2629004#2629004">what every Javascript programmer should know</a> on StackOverflow and found this <a href="http://stackoverflow.com/questions/1595611/how-to-properly-create-a-custom-object-in-javascript/1598077#1598077">useful pattern for using the more classic class/instance pattern</a> instead of Javascript&#8217;s standard prototype method.  I found the last example to be quite elegant and want to preserve it here for reference.</p>
<pre class="brush: jscript; title: ; notranslate">
function Shape(x, y) {
    var self = {};

    self.x = x;
    self.y = y;

    self.toString = function() {
        return 'Shape at ' + self.x + ', ' + self.y;
    };

    return self;
}

function Circle(x, y, r) {
  var self = Shape(x, y);

  self.r = r;

  var _baseToString = self.toString;
  self.toString = function() {
    return 'Circular ' + _baseToString(self) + ' with radius ' + r;
  };

  return self;
};

var mycircle = Circle(2, 3, 5);
console.log(mycircle.x === 2);
console.log(mycircle.y === 3);
console.log(mycircle.r === 5);
console.log(mycircle.toString());
</pre>
<p>With this pattern you have to use the &#8216;self&#8217; variable (which you can name anything you wish, the original was named &#8216;that&#8217;) to access and modify attributes of the class just like in Python.  Unlike Python you must explicitly declare the self variable at the beginning of the class and return it at the end.  Also if you are going to override an attribute in the parent class, but still need to access the parent attribute, you must rename it before overriding it, otherwise the reference to self.toString will end up in an infinite recursive loop.</p>
]]></content:encoded>
			<wfw:commentRss>http://nickzarr.com/blog4/2011/07/classes-and-instances-in-javascript-using-the-closure-method/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Getting WordPress SyntaxHighlighter Evolved to Validate</title>
		<link>http://nickzarr.com/blog4/2011/06/getting-wordpress-syntaxhighlighter-evolved-to-validate/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=getting-wordpress-syntaxhighlighter-evolved-to-validate</link>
		<comments>http://nickzarr.com/blog4/2011/06/getting-wordpress-syntaxhighlighter-evolved-to-validate/#comments</comments>
		<pubDate>Wed, 29 Jun 2011 18:34:54 +0000</pubDate>
		<dc:creator>Nick Zarczynski</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[wordpress]]></category>

		<guid isPermaLink="false">http://nickzarr.com/blog4/?p=1197</guid>
		<description><![CDATA[I&#8217;ve been using Alex Gorbatchev&#8217;s SyntaxHighlighter Evolved to post code to my blog since early this year. I&#8217;ve recently moved to self-hosting my blog and it was one of the first plugins I installed. I can&#8217;t say enough good things about it. It is a great plugin for simple syntax highlighting of anything from html [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been using Alex Gorbatchev&#8217;s <a href="http://wordpress.org/extend/plugins/syntaxhighlighter/">SyntaxHighlighter Evolved</a> to post code to my blog since early this year.  I&#8217;ve recently moved to self-hosting my blog and it was one of the first plugins I installed.  I can&#8217;t say enough good things about it.  It is a great plugin for simple syntax highlighting of anything from html to C to Python (though unfortunately not Scheme, maybe I should write a brush for that).</p>
<p>When I ran my blog through the validator at <a href="http://validator.w3.org/">w3c</a> I noticed two problems.  The first was with the Page Links To plugin using target=&#8221;_blank&#8221;.  This was simple enough to fix, just uncheck the &#8220;Open this link in a new window&#8221; box.  It&#8217;s probably better to let your visitors choose where they want their links to open, after all they can always middle click to open in a new tab.</p>
<p>The second problem was with SyntaxHighlighter Evolved&#8217;s use of &lt;meta id=&#8221;syntaxhighlighteranchor&#8221; &#8230;&gt; in the head tag.  This is not valid html and was a bit harder to fix.  I came across <a href="http://wordpress.org/support/topic/plugin-syntaxhighlighter-evolved-html-validation-fails">this post explaining the problem and rational behind the design</a> while Googling for a solution.  It seems that the id tag was used to provide a method for users to customize the plugin without editing the source files.  Since I quite enjoy digging into the source files, this wasn&#8217;t a show stopper for me.  In the end my solution was simple.  Remove the <em>feature</em> and get on with my life.</p>
<p>The first thing to do is to locate this line&#8230;</p>
<pre class="brush: jscript; title: ; notranslate">
		echo '&lt;meta id=&quot;syntaxhighlighteranchor&quot; name=&quot;syntaxhighlighter-version&quot; content=&quot;' . esc_attr( $this-&gt;pluginver ) . '&quot; /&gt;' . &quot;\n&quot;;
</pre>
<p>and remove the id=&#8221;syntaxhighlighteranchor&#8221; tag.</p>
<p>The plugin uses document.getElementById(&#8220;syntaxhighlighteranchor&#8221;) twice so you have to make two changes.  Instead of using the .insertBefore method to inject the css into the head element, use the .appendChild method.</p>
<pre class="brush: jscript; title: ; notranslate">
		document.getElementsByTagName(&quot;head&quot;)[0].insertBefore( corecss, document.getElementById(&quot;syntaxhighlighteranchor&quot;) );
// becomes
		document.getElementsByTagName(&quot;head&quot;)[0].appendChild( corecss );
</pre>
<p>and</p>
<pre class="brush: jscript; title: ; notranslate">
		document.getElementsByTagName(&quot;head&quot;)[0].insertBefore( themecss, document.getElementById(&quot;syntaxhighlighteranchor&quot;) );
// becomes
		document.getElementsByTagName(&quot;head&quot;)[0].appendChild( themecss );
</pre>
<p>You might want to put a comment in the sourcecode describing your change so you know what you did in the future in case it breaks.  If you really think you&#8217;re going to forget, you can always write a blog post about it too.</p>
<p>Again I can&#8217;t say enough good things about <a href="http://wordpress.org/extend/plugins/syntaxhighlighter/">SyntaxHighlighter Evolved</a>.  If you have an idea for a fix for this that preserves the original feature of being able to customize the plugin through css without delving into the sourcecode, please leave it in the comments.</p>
]]></content:encoded>
			<wfw:commentRss>http://nickzarr.com/blog4/2011/06/getting-wordpress-syntaxhighlighter-evolved-to-validate/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Jumping Into Javascript &#8211; Drawing JSONP Data on the Canvas</title>
		<link>http://nickzarr.com/blog4/2011/04/jumping-into-javascript-drawing-jsonp-data-on-the-canvas/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=jumping-into-javascript-drawing-jsonp-data-on-the-canvas</link>
		<comments>http://nickzarr.com/blog4/2011/04/jumping-into-javascript-drawing-jsonp-data-on-the-canvas/#comments</comments>
		<pubDate>Tue, 05 Apr 2011 06:57:38 +0000</pubDate>
		<dc:creator>Nick Zarczynski</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[canvas]]></category>
		<category><![CDATA[charting]]></category>
		<category><![CDATA[html5]]></category>
		<category><![CDATA[jumping into javascript]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://nickzarr.com/blog4/?p=1033</guid>
		<description><![CDATA[The last article in this series was a bit of a digression into the module pattern and namespaces in Javascript. This article will focus on a very simple charting algorithm. Now that we have the data to draw and know how to move things on the canvas, we need to focus on making the chart [...]]]></description>
			<content:encoded><![CDATA[<p>The <a href="http://nickzarr.com/blog4/2011/04/04/jumping-into-javascript-namespaces-we-should-have-more-of-these/">last article</a> in this series was a bit of a digression into the module pattern and namespaces in Javascript.  This article will focus on a very simple charting algorithm.</p>
<p>Now that we have the data to draw and know how to move things on the canvas, we need to focus on making the chart look more like a normal chart.  This post will focus on the drawing algorithms that will turn our data into a nice display and redrawing that same chart at different time periods/scales.  Here&#8217;s the screenshot representing our progress from last time.</p>
<p><img src="http://nickzarr.com/blog4/wp-content/uploads/2011/04/pytrade_alpha_014.png" alt="No Modifications" /></p>
<p>The first step is to find out the lowest value that will have to be drawn on the chart.  We can align all the rest of the values with the bottom of the chart if we subtract the lowest value from each value on the chart.  To do this we first have to traverse the sequence of data that will be shown and look for the lowest value.</p>
<pre class="brush: jscript; highlight: [25,26,27,28,29,30,31,32,33,34,35,36]; title: ; wrap-lines: false; notranslate">
var width = 600, height = 500
var chart = document.getElementById(&quot;chart&quot;);
var c = chart.getContext(&quot;2d&quot;);
chart.width = width; chart.height = height

//___________________________________________________________________________//
// Query and Init Procedures
//___________________________________________________________________________//

function getUrl(symbol) {
  return &quot;http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20csv%20where%20url%3D'http%3A%2F%2Fichart.finance.yahoo.com%2Ftable.csv%3Fs%3D&quot; + symbol + &quot;%26d%3D2%26e%3D27%26f%3D2011%26g%3Dd%26a%3D0%26b%3D1%26c%3D2000%26ignore%3D.csv'&amp;amp;format=json&amp;amp;callback=?&quot;;
}

$.getJSON(getUrl(&quot;ibm&quot;), init);

function init(result) {
  var data = result.query.results.row;
  drawRects(data, 1);
}

//___________________________________________________________________________//
// Chart Drawing Procedures
//___________________________________________________________________________//

function drawRects(d, s) {
  var e = s + 30;
  var low = d[s].col3;

  for (var i = s; i &lt; e; i++) {
    if (d[i].col3 &lt; low) { low = d[i].col3 }
  }

  for (var i = s; i &lt; e; i++) {
    c.fillRect(i*30, height-(d[i].col1-low), 20, d[i].col1 - d[i].col4);
  }
}
</pre>
<p><img src="http://nickzarr.com/blog4/wp-content/uploads/2011/04/pytrade_alpha_015.png" alt="Align at Bottom" /></p>
<p>The next thing to do is scale up the bar heights to match the height of the chart.  For this we also have to determine the highest high.  Then we take the difference between the highest high and the lowest low and divide the chart height by that number, this gives us our multiple.  Then we take the multiple and use it to compute the lower starting position as well as the height of each bar.</p>
<p>Before we were using the open data, however this won&#8217;t always give the lowest price.  On any day the stock price fell, the open will represent the highest price.  We don&#8217;t have to compute if the open is lower or higher than the close because our data gives us the low and high prices for the day.  This is also beneficial as the low or high from the day could be significantly lower/higher than the open or close.</p>
<p>Also we&#8217;ve been drawing our chart backward, to flip it we need to subtract the offset from the width of the chart.  In addition we should put in some color to tell what days are up or down.  Since code is probably the best description of this formula I&#8217;ll stop trying to explain it and just show you the algorithm.  I&#8217;m sure there is a cleaner/simpler solution (or maybe this solution is even too simple) however this can be updated a bit later down the road.</p>
<pre class="brush: jscript; highlight: [31,35,38,40,41,42,43,44,45,46]; title: ; wrap-lines: false; notranslate">
var width = 600, height = 500
var chart = document.getElementById(&quot;chart&quot;);
var c = chart.getContext(&quot;2d&quot;);
chart.width = width; chart.height = height

//chart.onclick = moveRects;

//___________________________________________________________________________//
// Query and Init Procedures
//___________________________________________________________________________//

function getUrl(symbol) {
  return &quot;http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20csv%20where%20url%3D'http%3A%2F%2Fichart.finance.yahoo.com%2Ftable.csv%3Fs%3D&quot; + symbol + &quot;%26d%3D2%26e%4D04%26f%3D2011%26g%3Dd%26a%3D0%26b%3D1%26c%3D2000%26ignore%3D.csv'&amp;amp;format=json&amp;amp;callback=?&quot;;
}

$.getJSON(getUrl(&quot;ibm&quot;), init);

function init(result) {
  var data = result.query.results.row;
  console.log(data[1].col0);
  drawRects(data, 1);
}

//___________________________________________________________________________//
// Chart Drawing Procedures
//___________________________________________________________________________//

function drawRects(d, s) {
  var e = s + 15;
  var low = d[s].col3;
  var high = d[s].col2;

  for (var i = s; i &lt; e; i++) {
    if (d[i].col3 &lt; low) { low = d[i].col3 }
    if (d[i].col2 &gt; high) { high = d[i].col2 }
  }

  var mul = height / (high - low);

  for (var i = e; i &gt; s; i--) {
    if (d[i].col1 &lt; d[i].col4) { c.fillStyle = &quot;#00f&quot;; }
    else { c.fillStyle = &quot;#f00&quot;; }
    c.fillRect(width - (i*30),
               height - (mul * (d[i].col1-low)),
               20,
               (mul * (d[i].col1 - d[i].col4)));
  }
}
</pre>
<p><img src="http://nickzarr.com/blog4/wp-content/uploads/2011/04/pytrade_alpha_017.png" alt="Simple Chart" /></p>
<p>And here&#8217;s the Yahoo Finance chart as comparison&#8230;</p>
<p><img src="http://nickzarr.com/blog4/wp-content/uploads/2011/04/pytrade_alpha_018.png" alt="Yahoo Finance Chart" /></p>
<p>Finally here&#8217;s a snapshot of pyTrade, the father of JamochaTrade.  Something similar to this is the ultimate goal of JamochaTrade.</p>
<p><img src="http://nickzarr.com/blog4/wp-content/uploads/2011/04/pytrade_alpha_019.png" alt="pyTrade" /></p>
<p>As you can see our chart now looks a lot more like a stock chart!  However, we still have a long way to go.  Wicks, labeled axes, hover tags and much more need to be added, not to mention different styles of charts (line, mountain, dot, etc.).  There are also a few bugs with our current implementation that need to be worked out.</p>
<p>The next article will concentrate on refactoring and debugging.  Notably we&#8217;ll move our code into a namespace, as was discussed in the previous article.  We&#8217;ll also rip out the drawing logic and put it into a function so we can make a more general drawing procedure that can handle different types of bar charts (Candlestick, OHLC, HLC).</p>
<p><a href="http://nickzarr.com/blog4/2011/11/jumping-into-javascript-good-news-and-bad-news/" title="Jumping into Javascript – Good news and bad news">GOTO Part 7 | Good news and bad news</a></p>
<p><a href="https://github.com/jacktrades/JamochaTrade">Get JamochaTrade on GitHub</a></p>
]]></content:encoded>
			<wfw:commentRss>http://nickzarr.com/blog4/2011/04/jumping-into-javascript-drawing-jsonp-data-on-the-canvas/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Jumping Into Javascript &#8211; Namespaces, we should have more of these</title>
		<link>http://nickzarr.com/blog4/2011/04/jumping-into-javascript-namespaces-we-should-have-more-of-these/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=jumping-into-javascript-namespaces-we-should-have-more-of-these</link>
		<comments>http://nickzarr.com/blog4/2011/04/jumping-into-javascript-namespaces-we-should-have-more-of-these/#comments</comments>
		<pubDate>Mon, 04 Apr 2011 20:52:31 +0000</pubDate>
		<dc:creator>Nick Zarczynski</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[canvas]]></category>
		<category><![CDATA[html5]]></category>
		<category><![CDATA[jumping into javascript]]></category>
		<category><![CDATA[module pattern]]></category>
		<category><![CDATA[namespaces]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://nickzarr.com/blog4/?p=1011</guid>
		<description><![CDATA[The last article dealt with cross-domain data retrieval. This article will be a short discussion about namespaces and the module pattern in Javascript. Here&#8217;s a snippet from the Zen of Python that I think should be included in some theoretical incantation of the Zen of Javascript: Namespaces are one honking great idea &#8212; let&#8217;s do [...]]]></description>
			<content:encoded><![CDATA[<p>The <a href="http://nickzarr.com/blog4/2011/03/27/jumping-into-javascript-same-origin-policy-jsonp-xmlhttprequest-and-cheating-with-jquery/">last article</a> dealt with cross-domain data retrieval.  This article will be a short discussion about namespaces and the module pattern in Javascript.</p>
<p>Here&#8217;s a snippet from the Zen of Python that I think should be included in some theoretical incantation of the Zen of Javascript:</p>
<blockquote><p>Namespaces are one honking great idea &#8212; let&#8217;s do more of those!</p></blockquote>
<p>Namespaces are an important concept in any programming language.  Programming without them is inevitably an exercise in tracking down hard-to-find bugs that occur when a definition is clobbered by an unrelated assignment.</p>
<p>Here&#8217;s the problem:  There is a single global namespace for all the scripts running in a page!</p>
<p>This means that defining: a = 42 in the file display.js will clobber the: a = 7 definition in database.js!  Let me restate that.  When you are creating global variables in a Javascript file, you must know about ALL the global variables created in ALL the other script files.</p>
<p>This may be possible for small apps that you write by yourself.  However for large apps and/or when multiple programmers are working on the same project, this is a nightmare.  Luckily there is a solution and it&#8217;s called the namespace pattern.</p>
<p>The namespace pattern is very similar to, but not quite the same as, the module pattern.  The module pattern is designed to allow private/public attributes of an object, which has benefits and drawbacks that are outside the scope of this article.</p>
<p>Links that describe these patterns can be found at the bottom of this page.  It is not within the scope of this series to describe all the aspects of the module pattern.  I will, however, give a short overview of the two approaches that I think are worthy of consideration.  The first is the module pattern and the second doesn&#8217;t have a name that I have found, so I&#8217;ll call it the Prototype Pattern.</p>
<p><strong>Module Pattern</strong></p>
<pre class="brush: jscript; title: ; notranslate">
var MODULE = (function () {
  // all code here
  return {
    // return everything you want to be public
  }
}());
</pre>
<p><strong>Prototype Pattern</strong></p>
<pre class="brush: jscript; title: ; notranslate">
var MODULE = {};
MODULE.variable = 42;
MODULE.fn = function (x) {return x*x};
</pre>
<p>With the module pattern you must declare everything you want to be public.  With the prototype approach you must prefix every attribute creation/access with the namespace.  I have read some articles that suggest that prototypes are more efficient than constructor functions.  I simply don&#8217;t know enough about Javascript at the moment to make that claim.  Please research this yourself if it is important to you, don&#8217;t take my word for it.</p>
<p>You may come across some &#8220;Module Pattern Considered Harmful&#8221; type articles when researching.  To save you some time here&#8217;s the argument: the module pattern is not a solution for every conceivable problem, therefore it should be avoided.  Some of these articles do raise valid use cases where the module pattern is not applicable, if you&#8217;re interested in that they are a good read.  Just don&#8217;t drink the kool-aid and believe that they are always useless/harmful.</p>
<p>Most of the issues with the module pattern revolve around private attributes.  I have spent most of my time programming in Python and Scheme and, in the general case, I haven&#8217;t had a need for private attributes.  However the real benefit of the module pattern (IMHO) is not private attributes, but avoiding the global namespace problem.  A problem for which the module pattern is an adequate solution.</p>
<p><a href="http://nickzarr.com/blog4/2011/04/05/jumping-into-javascript-drawing-jsonp-data-on-the-canvas/">GOTO Part 6 &#8211; Drawing JSONP Data on the Canvas</a></p>
<p><a href="https://github.com/jacktrades/JamochaTrade">Get JamochaTrade on GitHub</a></p>
<p>&nbsp;</p>
<h2>Links</h2>
<p><a href="http://www.youtube.com/watch?v=hQVTIJBZook">JavaScript: The Good Parts</a><br />
A Google Tech Talk given by Doug Crockford.  This talk is a great overview of the good and the bad of Javascript for experienced programmers.</p>
<p><a href="http://www.klauskomenda.com/code/javascript-programming-patterns/">Javascript Programming Patterns</a><br />
A good article that covers a number of methods of tackling the namespace problem.</p>
<p><a href="http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth">JavaScript Module Pattern: In-Depth</a><br />
More information about the module pattern.</p>
]]></content:encoded>
			<wfw:commentRss>http://nickzarr.com/blog4/2011/04/jumping-into-javascript-namespaces-we-should-have-more-of-these/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Jumping Into Javascript &#8211; Same Origin Policy, JSONP, XMLHttpRequest, and Cheating with jQuery</title>
		<link>http://nickzarr.com/blog4/2011/03/jumping-into-javascript-same-origin-policy-jsonp-xmlhttprequest-and-cheating-with-jquery/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=jumping-into-javascript-same-origin-policy-jsonp-xmlhttprequest-and-cheating-with-jquery</link>
		<comments>http://nickzarr.com/blog4/2011/03/jumping-into-javascript-same-origin-policy-jsonp-xmlhttprequest-and-cheating-with-jquery/#comments</comments>
		<pubDate>Mon, 28 Mar 2011 02:53:38 +0000</pubDate>
		<dc:creator>Nick Zarczynski</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[canvas]]></category>
		<category><![CDATA[getJSON]]></category>
		<category><![CDATA[html5]]></category>
		<category><![CDATA[JSONP]]></category>
		<category><![CDATA[jumping into javascript]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[Same Origin Policy]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[XMLHttpRequest]]></category>

		<guid isPermaLink="false">http://nickzarr.com/blog4/?p=954</guid>
		<description><![CDATA[In the last installment we successfully created an array of rectangle objects and moved them across the screen. This post will deal with retrieving JSONP data from a different domain. Figuring out how to accomplish this took me longer than I care to admit. I began researching the same origin policy around 14:00 today and [...]]]></description>
			<content:encoded><![CDATA[<p>In <a href="http://nickzarr.com/blog4/2011/03/27/jumping-into-javascript-objects-and-loops/">the last installment</a> we successfully created an array of rectangle objects and moved them across the screen.  This post will deal with retrieving JSONP data from a different domain.</p>
<p>Figuring out how to accomplish this took me longer than I care to admit.  I began researching the <a href="http://en.wikipedia.org/wiki/Same_origin_policy">same</a> <a href="http://stackoverflow.com/questions/3076414/ways-to-circumvent-the-same-origin-policy">origin</a> <a href="http://www.codeproject.com/KB/aspnet/JSONToJSONP.aspx">policy</a> around 14:00 today and after about 30 minutes I knew I needed to find a service that offered stock quotes in <a href="http://en.wikipedia.org/wiki/JSONP">JSONP</a> format, which allows cross-domain access.  I spent another 2 hours looking for a source of historical stock data in JSONP format before stumbling upon <a href="http://www.ibm.com/developerworks/web/library/wa-aj-jsonp2/index.html">this post by IBM developerWorks</a>.  That led me to the <a href="http://developer.yahoo.com/yql/console/#h=select%20*%20from%20csv%20where%20url%3D%27http%3A//ichart.finance.yahoo.com/table.csv%3Fs%3DGE%26d%3D2%26e%3D27%26f%3D2011%26g%3Dd%26a%3D0%26b%3D1%26c%3D2000%26ignore%3D.csv%27">Yahoo Query Language (YQL)</a> which is a SQL-like language for retrieving tons of different datasets in XML or JSONP format.  I proceeded to fool around with that for another 2 hours or so before figuring out how to <a href="http://www.gummy-stuff.org/Yahoo-data.htm">access Yahoo historical stock data</a> through YQL.</p>
<p>After 4 1/2 hours of looking for a new data source that was consumable by Javascript, I was not really in the mood to figure out the <a href="http://code.google.com/p/xmlhttprequest/">intricacies</a> <a href="http://www.boutell.com/newfaq/creating/ajaxfetch.html">of</a> <a href="http://www.ilinsky.com/articles/XMLHttpRequest/">portable</a> <a href="http://en.wikipedia.org/wiki/XMLHttpRequest">XMLHttpRequest</a> (which is bound to be a post, if not series, in itself).  So, at least for the moment, I cheated and included the jQuery library from Google for the sole purpose of retrieving the JSONP data.  Overkill?  Yes, most definitely.  For the moment though, it will have to do.  </p>
<p>Total time to get this very basic feature implemented?  6 1/2 hours, including 2 meals and a number of games of darts with the new blowgun I bought yesterday.  Moral of the story:  the security practices in Javascript can make your life a real pain in the&#8230;</p>
<p><strong>index.html</strong></p>
<pre class="brush: xml; highlight: [3]; title: ; wrap-lines: false; notranslate">
&lt;html&gt;
&lt;head&gt;
  &lt;script type=&quot;text/javascript&quot; src=&quot;https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.js&quot;&gt;&lt;/script&gt;
  &lt;title&gt;JamochaTrade - A Javascript stock charting program.&lt;/title&gt;
  &lt;style&gt;
    body {text-align: center;}
    canvas {border: 1px solid #000;}
  &lt;/style&gt;
&lt;/head&gt;
&lt;body&gt;
  &lt;canvas id=&quot;chart&quot;&gt;&lt;/canvas&gt;
  &lt;script src=&quot;chart.js&quot;&gt;&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p><strong>chart.js</strong></p>
<pre class="brush: jscript; highlight: [1,2,3,4,5,6,7,8,9,10,11,12,13]; title: ; wrap-lines: false; notranslate">
function getUrl(symbol) {
  // This should use the current date instead of a hardcoded date.
  return &quot;http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20csv%20where%20url%3D'http%3A%2F%2Fichart.finance.yahoo.com%2Ftable.csv%3Fs%3D&quot; + symbol + &quot;%26d%3D2%26e%3D27%26f%3D2011%26g%3Dd%26a%3D0%26b%3D1%26c%3D2000%26ignore%3D.csv'&amp;amp;format=json&amp;amp;callback=?&quot;;
}

function parseData(result) {
  // This returns an array of date objects the first row is labels.
  // For now use console.log so we can inspect the result in FireBug
  console.log(result.query.results.row);
}

// Loading and using jquery just for this is definately overkill.
$.getJSON(getUrl(&quot;ibm&quot;), parseData)

var chart = document.getElementById(&quot;chart&quot;);
var c = chart.getContext(&quot;2d&quot;);

chart.onclick = moveRects;

function drawRects() {
  for (var i in rects) {
    var r = rects[i];
    c.fillRect(r.x, r.y, r.width, r.height);
  }
}

function moveRects() {
  for (var i in rects) {
    rects[i].x += 20;
  }
  c.clearRect(0, 0, chart.width, chart.height);
  drawRects();
}

function Rect(x, y, width, height) {
  this.x = x;
  this.y = y;
  this.width = width;
  this.height = height;
}

var rects = [new Rect(10, 25, 20, 50), new Rect(40, 25, 20, 50)];

drawRects();
</pre>
<p>For the moment I considered it more instructive to simply simply spit the result out to the console so we can inspect it.  If you&#8217;re interested in seeing the full result object just use this code at line 9: console.log(result).</p>
<p>&nbsp;</p>
<h2>An Asynchronous Request</h2>
<p>jQuery&#8217;s getJSON procedure makes an asynchronous request for JSONP data.  What does this mean exactly?  For one, it means that some things you might have thought would work, simply won&#8217;t.  Take this as an example:</p>
<pre class="brush: jscript; title: ; notranslate">
var data = false;
$.getJSON(getUrl(&quot;ibm&quot;), function(result)
                           { data = result.query.results.row; } );

console.log(data);
</pre>
<p>In a synchronous environment one would expect <strong>data</strong> to contain the result of the getJSON request.  However, getJSON is an asynchronous method to fetch data.  This means that the variable <strong>data</strong> may or may not hold the result of getJSON depending on how long it takes getJSON to fetch the data.  If console.log is called before getJSON returns, the value of <strong>data</strong> will be false.</p>
<p>There are a number of solutions to this problem and I&#8217;m not really sure which is the best practice.  First, using jQuery&#8217;s ajax procedure and setting async to false <a href="http://api.jquery.com/jQuery.ajax/">will not work with JSONP</a>, just read the async entry in the link.  There&#8217;s also a note in there about synchronous requests possibly freezing the browser, which is the major downside of this next approach.</p>
<pre class="brush: jscript; title: ; notranslate">
data = false;
$.getJSON(getUrl(&quot;ibm&quot;), function(result)
                           { data = result.query.results.row; } );

while (data === false) { }

console.log(data);
</pre>
<p>Almost every time I try this I get the, &#8220;A script has become unresponsive&#8221; alert.  Though it does work, this is not the kind of user experience I want in my apps.</p>
<p>My next thought was to use a sleep function and check the value of data only so often to prevent the above error.  Well it turns out that the timer in Javascript is also implemented asynchronously!  In addition it would seem that there is no standard sleep function and no easy way of implementing one, which I find a bit odd, but I digress. </p>
<p>There are a few other approaches that I have found.  However there is only one that I actually like; just put the init code for the chart in the callback function!  Humorously this is what I intended to do from the beginning and what my first example does.  I wanted to make a simple example to show off here using a global to store the data.  Well it turns out that the simplest way to do that is to do it in the callback.</p>
<pre class="brush: jscript; title: ; notranslate">
$.getJSON(getUrl(&quot;ibm&quot;), init);

function init(result) {
  var data = result.query.results.row;
  // do something with your data here
  console.log(data);
}
</pre>
<p>This approach may require rethinking the design of your app a bit, but it&#8217;s usually pretty simple.  One approach is to simply put all your top-level commands inside a main or init function and use that as your callback function.  A discussion of the different approaches to asynchronous code is outside the scope of this article.</p>
<p>That just about concludes this part of the Jumping Into Javascript series.  Before ending this, I&#8217;ll leave you with the updated code.  I have temporarily removed the ability to move items on the canvas, however the chart is now drawn from real data.  It still doesn&#8217;t look all that great because I used a very naïve drawing algorithm to keep things simple and focused on fetching and handling the data, but you should get the idea.</p>
<pre class="brush: jscript; title: ; wrap-lines: false; notranslate">
var width = 600, height = 500
var chart = document.getElementById(&quot;chart&quot;);
var c = chart.getContext(&quot;2d&quot;);
chart.width = width; chart.height = height

//chart.onclick = moveRects;

//___________________________________________________________________________//
// Query and Init Procedures
//___________________________________________________________________________//

function getUrl(symbol) {
  return &quot;http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20csv%20where%20url%3D'http%3A%2F%2Fichart.finance.yahoo.com%2Ftable.csv%3Fs%3D&quot; + symbol + &quot;%26d%3D2%26e%3D27%26f%3D2011%26g%3Dd%26a%3D0%26b%3D1%26c%3D2000%26ignore%3D.csv'&amp;amp;format=json&amp;amp;callback=?&quot;;
}

$.getJSON(getUrl(&quot;ibm&quot;), init);

function init(result) {
  var data = result.query.results.row;
  drawRects(data, 1);
}

//___________________________________________________________________________//
// Chart Drawing Procedures
//___________________________________________________________________________//

function drawRects(d, s) {
  var e = s + 30;
  for (var i = s; i &lt; e; i++) {
    c.fillRect(i*30, d[i].col1, 20, d[i].col1 - d[i].col4);
  }
}
</pre>
<p>A quick screenshot too&#8230;</p>
<p><img src="http://nickzarr.com/blog4/wp-content/uploads/2011/04/pytrade_alpha_014.png" alt="Screenshot" /></p>
<p>With retrieving and handling data out of the way, the next article will likely be a short digression into the namespace pattern.  After that I will most likely cover a few possible implementations of the chart drawing algorithm and play around with Javascript&#8217;s first-class functions.</p>
<p><a href="http://nickzarr.com/blog4/2011/04/04/jumping-into-javascript-namespaces-we-should-have-more-of-these/">GOTO Part 5 &#8211; Namespaces we should have more of these</a></p>
<p><a href="https://github.com/jacktrades/JamochaTrade">Get JamochaTrade on GitHub</a></p>
]]></content:encoded>
			<wfw:commentRss>http://nickzarr.com/blog4/2011/03/jumping-into-javascript-same-origin-policy-jsonp-xmlhttprequest-and-cheating-with-jquery/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Jumping Into Javascript &#8211; Objects and Loops</title>
		<link>http://nickzarr.com/blog4/2011/03/jumping-into-javascript-objects-and-loops/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=jumping-into-javascript-objects-and-loops</link>
		<comments>http://nickzarr.com/blog4/2011/03/jumping-into-javascript-objects-and-loops/#comments</comments>
		<pubDate>Sun, 27 Mar 2011 20:32:05 +0000</pubDate>
		<dc:creator>Nick Zarczynski</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[canvas]]></category>
		<category><![CDATA[html5]]></category>
		<category><![CDATA[jumping into javascript]]></category>
		<category><![CDATA[loops]]></category>
		<category><![CDATA[objects]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://nickzarr.com/blog4/?p=936</guid>
		<description><![CDATA[In the last post I used an array to model a rectangle. This worked for a quick test, however the rectangle is probably best modeled as an object. Especially considering that the rectangle is only part of a candlestick bar that also must include a wick, or line. In this part we&#8217;ll turn the rect [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://nickzarr.com/blog4/2011/03/26/jumping-into-javascript-moving-objects-on-the-canvas/">In the last post</a> I used an array to model a rectangle.  This worked for a quick test, however the rectangle is probably best modeled as an object.  Especially considering that the rectangle is only part of a candlestick bar that also must include a wick, or line.  In this part we&#8217;ll turn the rect into an object, then move on to creating a bunch of them and moving them all at the same time using a loop.</p>
<p>The first thing we&#8217;ll do is convert rect to be an object.  Objects in Javascript are different than objects in many other languages.  In many languages objects are class based, the object system in Javascript is prototype based.  Very quickly what that means is that, in a class based object system, there is the abstract definition of an object (the class definition) and there are instances of objects defined by the class.  In a prototype based system there is no distinction between the two.</p>
<p>In many practical ways these two systems are very similar, however there are some differences that may trip you up.  I encourage you to <a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Details_of_the_Object_Model#Class-Based_vs._Prototype-Based_Languages">read more about the differences and similarities</a>.  Unfortunately I can&#8217;t go much more in-depth than that here.</p>
<pre class="brush: jscript; highlight: [7,12,16,17,18,19,20,21,22,23]; title: ; notranslate">
var chart = document.getElementById(&quot;chart&quot;);
var c = chart.getContext(&quot;2d&quot;);

chart.onclick = moveRect;

function drawRect() {
  c.fillRect(rect.x,rect.y,rect.width,rect.height);
}

function moveRect() {
  c.clearRect(0, 0, chart.width, chart.height);
  rect.x += 20;
  drawRect();
}

function Rect(x, y, width, height) {
  this.x = x;
  this.y = y;
  this.width = width;
  this.height = height;
}

var rect = new Rect(10, 25, 20, 50);

drawRect(rect)
</pre>
<p>As you can see we simply use a function to construct a <strong>Rect</strong> object.  The <strong>this</strong> keyword is similar to <strong>self</strong> in Python and signifies that the variable is an attribute of the object.  To create a new object we have to use the <strong>new</strong> keyword, this can be seen in the line: <strong>var rect = new Rect(10, 25, 20, 50);</strong>.</p>
<p>Other than these few modifications, nothing else has changed.  <strong>rect</strong> is still used as a global variable and the functions <strong>drawRect</strong> and <strong>moveRect</strong> operate directly on rect.  The next thing we&#8217;ll do is create a global array where we can store a number of Rects.  This will require changing almost everything, however most changes will be minor.</p>
<pre class="brush: jscript; highlight: [4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,28,29,30]; title: ; notranslate">
var chart = document.getElementById(&quot;chart&quot;);
var c = chart.getContext(&quot;2d&quot;);

chart.onclick = moveRects;

function drawRects() {
  for (var i in rects) {
    var r = rects[i];
    c.fillRect(r.x, r.y, r.width, r.height);
  }
}

function moveRects() {
  for (var i in rects) {
    rects[i].x += 20;
  }
  c.clearRect(0, 0, chart.width, chart.height);
  drawRects();
}

function Rect(x, y, width, height) {
  this.x = x;
  this.y = y;
  this.width = width;
  this.height = height;
}

var rects = [new Rect(10, 25, 20, 50), new Rect(40, 25, 20, 50)];

drawRects();
</pre>
<p>Make sure that you use the <strong>new</strong> keyword when you create new objects, even when they are in an array.  I spent at least 10 minutes trying to figure out what I was doing wrong in the for loop, just to realize that I did not use the new keyword when I initialized the array!</p>
<p>Also I noticed that, at least some, Javascript implementations are very forgiving regarding errors.  Until now I&#8217;ve been passing rect as an argument to drawRect in the moveRect function.  The drawRect function does not expect any arguments, yet I am allowed to give it one without complaint.  I can see this &#8220;feature&#8221; being problematic down the road, however I can also see that it might be necessary with all the different non-conforming implementations out there.  I have since gone back and fixed this in previous posts.</p>
<p>Since we&#8217;ve already covered objects and arrays, the only thing new here is the <strong>for loop</strong>.  There are two methods of invoking the for loop in Javascript.  The one that I used above is&#8230;</p>
<pre class="brush: jscript; title: ; notranslate">
for (var i in sequence) {
  // body;
  // use sequence[i] to access elements
}
</pre>
<p>One thing to note with this method is that <strong>i</strong> is not bound to the n<sup>th</sup> element in sequence, rather <strong>i</strong> is simply a counter.  This method is basically a shorthand for the next method which is more similar to C syntax&#8230;</p>
<pre class="brush: jscript; title: ; notranslate">
for (var i = 0; i &gt; sequence.length; i++) {
  // body;
  // use sequence[i] to access elements
}
</pre>
<p>This is the standard for loop syntax available in many languages.  No matter which method you use you must still use sequence[i] to access the elements.  The (var i in sequence) syntax does <strong>not</strong> act like Python&#8217;s for i in sequence.</p>
<p>The next post will explore downloading and manipulating stock data.  However I have run into a small problem that I haven&#8217;t been able to solve in &lt;30 minutes of searching.  It seems that the <a href="http://en.wikipedia.org/wiki/Same_origin_policy">same origin policy</a> will prevent me from downloading historical data from Google Finance.  From what I&#8217;m reading I need to find a source of historical quotes that offers the data in <a href="http://en.wikipedia.org/wiki/JSONP">JSONP</a> (or <a href="http://en.wikipedia.org/wiki/Cross-Origin_Resource_Sharing">CORS</a>) which will allow cross domain access.  While I can understand the security implications of allowing arbitrary cross-domain access, this part of the app (which was trivial in Python) is a real pain in Javascript.</p>
<p><a href="http://nickzarr.com/blog4/2011/03/27/jumping-into-javascript-same-origin-policy-jsonp-xmlhttprequest-and-cheating-with-jquery/">GOTO Part 4 &#8211; Same Origin Policy, JSONP, XMLHttpRequest, and Cheating with jQuery</a></p>
<p><a href="https://github.com/jacktrades/JamochaTrade">Get JamochaTrade on GitHub</a></p>
<p>&nbsp;</p>
<h2>Links</h2>
<p><a href="https://developer.mozilla.org/en/Introduction_to_Object-Oriented_JavaScript">Introduction to Object-Oriented JavaScript</a></p>
]]></content:encoded>
			<wfw:commentRss>http://nickzarr.com/blog4/2011/03/jumping-into-javascript-objects-and-loops/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Jumping Into Javascript &#8211; Moving Objects on the Canvas</title>
		<link>http://nickzarr.com/blog4/2011/03/jumping-into-javascript-moving-objects-on-the-canvas/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=jumping-into-javascript-moving-objects-on-the-canvas</link>
		<comments>http://nickzarr.com/blog4/2011/03/jumping-into-javascript-moving-objects-on-the-canvas/#comments</comments>
		<pubDate>Sun, 27 Mar 2011 04:54:04 +0000</pubDate>
		<dc:creator>Nick Zarczynski</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[canvas]]></category>
		<category><![CDATA[html5]]></category>
		<category><![CDATA[jumping into javascript]]></category>
		<category><![CDATA[loops]]></category>
		<category><![CDATA[objects]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://nickzarr.com/blog4/?p=909</guid>
		<description><![CDATA[In the first part of Jumping Into Javascript, we created a simple html page with a canvas element on it and drew a single square. In this part we will concentrate on moving objects that we have drawn. The concept of moving an object on the canvas is a bit of a misnomer. We actually [...]]]></description>
			<content:encoded><![CDATA[<p>In the <a href="http://nickzarr.com/blog4/2011/03/26/jumping-into-javascript/">first part of Jumping Into Javascript</a>, we created a simple html page with a canvas element on it and drew a single square.  In this part we will concentrate on moving objects that we have drawn.</p>
<p>The concept of moving an object on the canvas is a bit of a misnomer.  We actually won&#8217;t move anything at all, instead we must clear the canvas (or part of it) and repaint the object in a new location.  Let&#8217;s look at the simplest code I could come up with that accomplishes this.</p>
<p><strong>chart.js</strong></p>
<pre class="brush: jscript; highlight: [5,6]; title: ; notranslate">
var chart = document.getElementById(&quot;chart&quot;);
var c = chart.getContext(&quot;2d&quot;);

c.fillRect(10, 25, 20, 50);
c.clearRect(0, 0, chart.width, chart.height);
c.fillRect(30, 25, 20, 50);
</pre>
<p>This code starts by drawing a rectangle, then c.clearRect(0, 0, chart.width, chart.height) clears the canvas, then it draws another rectangle 20 pixels over to the right.  If you run this code, you probably won&#8217;t see anything but the final rectangle.  This is because it is running very fast.  To see it we need to slow things down a bit.</p>
<p>There are a number of ways we could achieve this.  We could set an event loop and move the rectangle on each loop, or we could set a timer between draws.  However I&#8217;m going to use an event handler to call a function that clears the canvas and redraws the rectangle.</p>
<p><strong>chart.js</strong></p>
<pre class="brush: jscript; highlight: [5,6,7,8,9,10]; title: ; notranslate">
var chart = document.getElementById(&quot;chart&quot;);
var c = chart.getContext(&quot;2d&quot;);
c.fillRect(10, 25, 20, 50);

chart.onclick = moveRect;

function moveRect() {
  c.clearRect(0, 0, chart.width, chart.height);
  c.fillRect(30, 25, 20, 50);
}
</pre>
<p>When you click on the canvas you will see the rectangle &#8220;move&#8221; a bit to the right.  This illustrates a few things about Javascript that I haven&#8217;t covered.  First moveRect is an example of how functions are defined in Javascript.  You can also define functions like this&#8230;</p>
<pre class="brush: jscript; title: ; notranslate">
var moveRect = function() { //body; }
</pre>
<p>&#8230; <a href="http://stackoverflow.com/questions/336859/javascript-var-functionname-function-vs-function-functionname">see here for an explanation of the difference</a>.  This little snippet also hints to us that functions are first-class values in Javascript, but I won&#8217;t get into that now.</p>
<p>Also this demonstrates one of the ways to set an event handler.  This sets the function <strong>moveRect</strong> to be called whenever the canvas is left clicked.  This method of event handling will work with any modern browser.</p>
<p>Another way to accomplish event handling is to use the inline method.  This is the oldest way to set handlers in Javascript.  If you have to maintain compatibility with very old browsers you will be forced to use this method.  Here&#8217;s a <a href="http://www.quirksmode.org/js/introevents.html">link to more info on the inline method</a> and an example&#8230;</p>
<pre class="brush: xml; title: ; notranslate">
&lt;canvas id=&quot;chart&quot; onclick=&quot;moveRect();&quot;&gt;&lt;/canvas&gt;
</pre>
<p>So far we&#8217;ve got our rectangle to &#8220;move&#8221; once when the canvas is clicked on.  However it will not move any further, no matter how many clicks occur.  The reason for this is that we are not incrementing the x position of the rectangle, rather the new position is hardcoded into the moveRect function.</p>
<p>Even though we see a rectangle on the screen, in our source code there is really no notion of the rectangle as a separate entity.  There are a variety of options to fix this behavior, we could code the rectangle as an object, or use a closure, or even use 4 different variables to hold the position and size of our rectangle.  I&#8217;ll be covering some of those options later, but for now I want to focus on <a href="http://nickzarr.com/blog4/2011/02/20/what-in-the-hell-are-arrays/">arrays</a>.</p>
<p>Temporarily I&#8217;ll use an array to hold the values of the rectangle and a variable to hold the array.  I&#8217;ll call it <strong>rect</strong> for now.  Because the fillRect function does not accept an array as a parameter, we&#8217;ll need to define a function <strong>drawRect</strong> that will call fillRect with the correct values.  To keep things simple, I&#8217;ll use rect as a global variable.</p>
<pre class="brush: jscript; title: ; notranslate">
var chart = document.getElementById(&quot;chart&quot;);
var c = chart.getContext(&quot;2d&quot;);

chart.onclick = moveRect;

function drawRect() {
  c.fillRect(rect[0],rect[1],rect[2],rect[3]);
}

function moveRect() {
  c.clearRect(0, 0, chart.width, chart.height);
  rect[0] += 20;
  drawRect();
}

var rect = [10, 25, 20, 50];

drawRect()
</pre>
<p>When you run this code you&#8217;ll notice that the rectangle keeps moving to the right every time you click the canvas.  This is exactly the behavior we were looking for here.</p>
<p>Once again there are a few new concepts here.  <strong>var rect = [10, 25, 20, 50];</strong> creates an array and assigns it to the variable rect.  You do not have to specify the number of elements in the array and it is also resizable.  Indexing into an array is similar to most Algol inspired languages using <strong>varName[n]</strong> to access the n<sup>th</sup> element of an array stored in varName.  <strong>+=</strong> also works as expected and destructively increments the value of the index n by the value of the right hand expression.  This code also gives you a quick peek at the scoping rules used in Javascript, however a through overview will have to wait for a later article.  </p>
<p>That quick overview concludes this post on moving objects on a canvas and arrays.  In the next post I&#8217;ll probably cover objects and loops and create more rectangles to move about.</p>
<p><a href="http://nickzarr.com/blog4/2011/03/27/jumping-into-javascript-objects-and-loops/">GOTO &#8211; Part 3 &#8211; Objects and Loops</a></p>
<p><a href="https://github.com/jacktrades/JamochaTrade">Get JamochaTrade on GitHub</a></p>
<p>&nbsp;</p>
<h2>Links</h2>
<p><a href="http://www.hunlock.com/blogs/Mastering_Javascript_Arrays">Mastering Javascript Arrays</a></p>
<p><a href="http://www.quirksmode.org/js/function.html">QuirksMode.org &#8211; Functions</a></p>
]]></content:encoded>
			<wfw:commentRss>http://nickzarr.com/blog4/2011/03/jumping-into-javascript-moving-objects-on-the-canvas/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Jumping Into Javascript</title>
		<link>http://nickzarr.com/blog4/2011/03/jumping-into-javascript/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=jumping-into-javascript</link>
		<comments>http://nickzarr.com/blog4/2011/03/jumping-into-javascript/#comments</comments>
		<pubDate>Sat, 26 Mar 2011 18:01:05 +0000</pubDate>
		<dc:creator>Nick Zarczynski</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[canvas]]></category>
		<category><![CDATA[html5]]></category>
		<category><![CDATA[jumping into javascript]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://nickzarr.com/blog4/?p=891</guid>
		<description><![CDATA[A few weeks ago I decided to post my first question to stackoverflow&#8230; How does a self-taught programmer know when he&#8217;s ready to look for a job? The responses I got were very encouraging, but one in particular pointed out some shortcomings in my education. To paraphrase, it instructed me to look around at job [...]]]></description>
			<content:encoded><![CDATA[<p>A few weeks ago I decided to post my <a href="http://programmers.stackexchange.com/questions/54959/how-does-a-self-taught-programmer-know-when-hes-ready-to-look-for-a-job">first question to stackoverflow</a>&#8230;</p>
<blockquote><p>How does a self-taught programmer know when he&#8217;s ready to look for a job?</p></blockquote>
<p>The responses I got were very encouraging, but one in particular pointed out some shortcomings in my education.  To paraphrase, it instructed me to look around at job offerings and compare the skill set employer&#8217;s are looking for to my own.  This was a bit disheartening to me as I&#8217;ve been focusing mainly on theory and AI and found that my skills are not all that marketable in an environment that is dominated by web and database programming.</p>
<p>This endeavor is an attempt to remedy that problem, or at least demonstrate to future employers and myself, that I can pick up these technologies relatively quickly.  When I learn a new technology/language/framework I usually prefer to start with a project that can be done simply but can also scale up, rather than simply following along with a tutorial or book.  </p>
<p>For this purpose I will be writing a Javascript version of <a href="http://nickzarr.com/blog4/my-code/#pyTrade">pyTrade</a>, which will not be a port, but a complete rewrite to allow me to understand the language better.  It wasn&#8217;t too long ago that I wrote pyTrade, so a lot of it is still fresh in my mind, however it&#8217;s been long enough that at least some of the details escape me and I will do my best not to look at the source code.</p>
<p>I&#8217;ll be writing this in tutorial fashion to help reinforce the concepts that I&#8217;ll be learning and to let others follow along if they wish.  This will not be a beginner&#8217;s introduction to Javascript.  I&#8217;m assuming that the reader is intimately familiar with at least one Algol inspired language.  My background is mainly Python and Scheme with a little C, so you may see Javascript idioms compared against their counterparts in these languages.  </p>
<p>Since I don&#8217;t want to constantly refer to this project as &#8220;this project&#8221;, for now it will be codenamed JamochaTrade.  Maybe I just didn&#8217;t think hard enough, but I couldn&#8217;t come up with a short prefix that didn&#8217;t make it sound like this was implemented in Java.  Not that JamochaTrade satisfies that criteria, but I like it as a codename.</p>
<p>&nbsp;</p>
<h2>First Step to JamochaTrade</h2>
<p>As I said earlier, I&#8217;m going to start out with the simplest thing I can and work up from there.  The simplest thing I can think of to start with is the html shell page that will allow people to access JamochaTrade.  Without further ado here&#8217;s the shell&#8230;</p>
<p><strong>index.html</strong></p>
<pre class="brush: xml; title: ; notranslate">
&lt;html&gt;
&lt;head&gt;
  &lt;title&gt;JamochaTrade - A Javascript stock charting program.&lt;/title&gt;
  &lt;style&gt;
    body {text-align: center;}
    canvas {border: 1px solid #000;}
  &lt;/style&gt;
&lt;/head&gt;
&lt;body&gt;
  &lt;canvas id=&quot;chart&quot;&gt;&lt;/canvas&gt;
  &lt;script src=&quot;chart.js&quot;&gt;&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>I&#8217;ve saved this code in a file named &#8220;index.html&#8221; and also created a blank file named &#8220;chart.js&#8221; where the Javascript will eventually reside.  This code doesn&#8217;t do much and I think it&#8217;s relatively self-explanatory so I won&#8217;t go over it, except to say the important part of this shell is that we create a canvas and give it the id of <strong>chart</strong>.</p>
<p>Now that we have a canvas, my first goal is to draw something on it.  Since my preferred charting style is the candlestick chart, I&#8217;ll start by figuring out how to draw a box on the canvas.  To do this we need to do 3 things in our chart.js file, first we need to get the reference to the canvas from the dom, then we need to get the <strong>context</strong> from the canvas and finally we need to draw a box.</p>
<p>What is a context?  The simplest way to think about a context is as an API.  A context provides methods of drawing on the canvas, different contexts provide different methods of drawing.  That&#8217;s the best explanation I have at the moment, I&#8217;ll probably explain it more throughly later.</p>
<p>Currently there is only one universally supported context for the canvas, which is the &#8220;2d&#8221; context.  At some point in the future there will also be a &#8220;3d&#8221; context that will allow 3d graphics to be displayed in the browser.  Since that only exists in a few vendor-specific instances right now I&#8217;ll ignore that from here on out.</p>
<p><strong>chart.js</strong></p>
<pre class="brush: jscript; title: ; notranslate">
var chart = document.getElementById(&quot;chart&quot;);
var c = chart.getContext(&quot;2d&quot;);
c.fillRect(10, 25, 20, 50);
</pre>
<p>The first line above simply gets the <strong>chart</strong> object from the dom tree.  The second line sets the chart&#8217;s 2d context to the variable <strong>c</strong>.  I chose <strong>c</strong> because it is short and we will be using it in many of our drawing calls, also it can be thought of as short for context, canvas and chart which works out pretty well if I do say so myself.</p>
<p>Finally we draw our first object onto the canvas.  The <strong>fillRect</strong> procedure is used to do the actual drawing.  There&#8217;s two common way&#8217;s I&#8217;ve come across drawing rectangles in GUI programs, the first is to specify the <strong>x</strong> and <strong>y</strong> starting point of one corner of the rectangle and the <strong>x</strong> and <strong>y</strong> point of the opposite side (Left/Top/Right/Bottom).  The other way, and the way the 2d context in Javascript works, is to specify the <strong>x</strong> and <strong>y</strong> starting position and then the length of the rectangle along the <strong>x</strong> axis and the <strong>y</strong> axis (X/Y/Width/Height).  </p>
<p>The easiest way to test which coordinate system is being used is to give large numbers for the first 2 parameters and small negative numbers for the next 2 parameters, like (100, 100, -10, -10).  If the resulting rectangle fills the entire top left corner you are using the (Left/Top/Right/Bottom) coordinate system, if the rectangle is small and off of the edge you are using the (X/Y/Width/Height) coordinate system.</p>
<p>With that lengthy discussion out of the way the first Jumping Into Javascript post has reached its conclusion.  The next post will cover moving the rectangle as well as a brief overview of arrays.</p>
<p><a href="http://nickzarr.com/blog4/2011/03/26/jumping-into-javascript-moving-objects-on-the-canvas/">GOTO &#8211; Part 2 &#8211; Moving Objects on the Canvas</a></p>
<p><a href="https://github.com/jacktrades/JamochaTrade">Get JamochaTrade on GitHub</a></p>
<p>&nbsp;</p>
<h2>Links</h2>
<p><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html">WhatWG Canvas Standard/Reference</a></p>
<p><a href="http://diveintohtml5.org/canvas.html">Dive Into HTML5 &#8211; Canvas</a></p>
<p><a href="http://michalbe.blogspot.com/2010/09/simple-game-with-html5-canvas-part-1.html">Michal Budzynski: Simple game with HTML5 Canvas Tutorial</a></p>
<p><a href="http://stackoverflow.com/questions/4111806/how-do-you-like-to-format-rectangle-coordinates-for-output">A stackoverflow discussion of coordinate systems.</a></p>
]]></content:encoded>
			<wfw:commentRss>http://nickzarr.com/blog4/2011/03/jumping-into-javascript/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

