<?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>Less code, more sleep &#187; javascript</title>
	<atom:link href="http://emmett.be/thewebdev/tags/javascript/feed" rel="self" type="application/rss+xml" />
	<link>http://emmett.be/thewebdev</link>
	<description>Tales of an insomniac coder</description>
	<lastBuildDate>Mon, 26 Jul 2010 22:48:29 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Caveats of the JS Module Pattern</title>
		<link>http://emmett.be/thewebdev/archives/96</link>
		<comments>http://emmett.be/thewebdev/archives/96#comments</comments>
		<pubDate>Wed, 14 Jul 2010 20:19:59 +0000</pubDate>
		<dc:creator>Emmett Pickerel</dc:creator>
				<category><![CDATA[Frontend]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[programming patterns]]></category>

		<guid isPermaLink="false">http://emmett.be/thewebdev/?p=96</guid>
		<description><![CDATA[Why the Javascript module pattern might not always be the best choice]]></description>
			<content:encoded><![CDATA[<p>Javascript <a href="http://www.wait-till-i.com/2007/07/24/show-love-to-the-module-pattern/">modules</a> are a nifty construct which I was lucky enough to learn firsthand from <a href="http://crockford.com/">Douglas Crockford</a> in his (then) small classes at Yahoo c2005. He didn&#8217;t use the term &#8220;module pattern&#8221; then &#8212; I expect he hadn&#8217;t thought of the phrase yet. It was just a way to have private variables and methods.</p>
<p>I still love them, but I have some caveats with regards to using them for non-<a href="http://emmett.be/thewebdev/what-is-a-singleton">singleton</a> objects.</p>
<p>First, what is a module?</p>
<pre class="code"><code>var counter = function(){
    var my = {
        count: 0,
        max: 5,
        isPastMax: function(){
            return this.count &gt; this.max;
        }
    };
    //This is what gets assigned to the variable "counter"
    return {
        getCount: function(){
            return my.count;
        },
        reset: function(){
            my.count = 0;
        },
        increment: function(){
            my.count++;
            if (my.isPastMax()) {
                this.reset();
            }
        }
    };
}(); //NOTE the (). That makes the outer function run and return immediately</code></pre>
<p>A module is nothing more than a function which returns a public API object which, through the magic of closure, has access to truly private methods and variables. Here I&#8217;ve put them all as properties of private variable <code>my</code>.</p>
<p><code>counter</code> is now a singleton object that maintains a counter state privately. No more methods can be added to it which reach anything in <code>my</code> that we haven&#8217;t explicitly allowed.</p>
<p>This is all well and good. But what if we want more than one counter? Let&#8217;s take off the trailing <code>()</code> so that we have a factory that produces <code>counter</code>s:</p>
<pre class="code"><code>var Counter = function(){
   //just as above
}; //NOTE the absence of ()!
var instances = [];
for (var i=0; i&lt;100; i++) {
    instances.push(Counter());
}</code></pre>
<p>Now we have 100 instances of the <code>Counter</code> module!</p>
<p>Unfortunately, the encapsulation has come with a price in this case. Every function we defined within <code>Counter</code> has to be created again and occupy more memory!</p>
<p>Sometimes this is acceptable, if the number to be created is low and the module is small. If you&#8217;ve got a module that goes on for a few pages and you intend to make a few dozen instances, expect to be eating up substantially more memory than a similar feature using a non-encapsulated object, like so:</p>
<pre class="code"><code>var Counter = {
    _count: 0,
    _max: 5,
    _isPastMax: function(){
        return this._count &gt; this._max;
    },
    reset: function(){
        this._count = 0;
    },
    increment: function(){
        this._count++;
    },
    getCount: function(){
        return this._count;
    }
};
Object.extend = Object.extend || function(a, b){
    for (var k in b) {
        if (b.hasOwnProperty(k)) { a[k] = b[k]; }
    }
    return a;
};
var instances = [];
for (var i=0; i&lt;100; i++) {
    instances.push(
        Object.extend({}, Counter)
    );
}</code></pre>
<p>All of the functions exist only once in memory, referenced by the individual instance objects.</p>
<p>Make no doubt: the module pattern is a tool that every good Javascript developer should understand. It provides excellent encapsulation that can&#8217;t be externally broken. It&#8217;s not without its drawbacks, however.</p>
]]></content:encoded>
			<wfw:commentRss>http://emmett.be/thewebdev/archives/96/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Resize-to-window web apps</title>
		<link>http://emmett.be/thewebdev/archives/93</link>
		<comments>http://emmett.be/thewebdev/archives/93#comments</comments>
		<pubDate>Tue, 04 May 2010 20:07:17 +0000</pubDate>
		<dc:creator>Emmett Pickerel</dc:creator>
				<category><![CDATA[Frontend]]></category>
		<category><![CDATA[Styling]]></category>
		<category><![CDATA[css]]></category>
		<category><![CDATA[Flash-like UI]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://emmett.be/thewebdev/?p=93</guid>
		<description><![CDATA[One of the things Flash designers have had which web developers have not is the ability to retarget an application to any viewport size desired. I&#8217;ve been saddled with implementing a by such a Flash designer for deployment in HTML/CSS/JS on QTwebkit. What&#8217;s amazing is that I&#8217;ve had some degree of success with it. I ]]></description>
			<content:encoded><![CDATA[<p>One of the things Flash designers have had which web developers have not is the ability to retarget an application to any viewport size desired. I&#8217;ve been saddled with implementing a by such a Flash designer for deployment in HTML/CSS/JS on QTwebkit.</p>
<p>What&#8217;s amazing is that I&#8217;ve had some degree of success with it. I can&#8217;t show a demo yet, but imagine that a fully animated, complicated application smoothly scales, centres, and otherwise behaves more or less like you&#8217;d expect Flash to.</p>
<p>To be sure, there are some sketchy areas. Webkit&#8217;s positioning math can be very sloppy if you need precision (my design does). Any container that&#8217;s affected by font size is going to change a little (not always bad).</p>
<p>Watch here for a demonstration of this soon, along with a bit of how-to.</p>
]]></content:encoded>
			<wfw:commentRss>http://emmett.be/thewebdev/archives/93/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Improved jquery ajax error reporting</title>
		<link>http://emmett.be/thewebdev/archives/64</link>
		<comments>http://emmett.be/thewebdev/archives/64#comments</comments>
		<pubDate>Sat, 12 Dec 2009 16:02:22 +0000</pubDate>
		<dc:creator>Emmett Pickerel</dc:creator>
				<category><![CDATA[Frontend]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[json]]></category>

		<guid isPermaLink="false">http://emmett.be/thewebdev/?p=64</guid>
		<description><![CDATA[jQuery is a great library, and I highly recommend it after 6 months of use. One of the problems I&#8217;ve had with it, however, is its poor error reporting on ajax requests. While you can subscribe to the global event ajaxError, there&#8217;s nothing to tell you what went wrong. Specifically, I&#8217;ve wanted a way to ]]></description>
			<content:encoded><![CDATA[<p>jQuery is a great library, and I highly recommend it after 6 months of use. One of the problems I&#8217;ve had with it, however, is its poor error reporting on ajax requests. While you can subscribe to the global event <code>ajaxError</code>, there&#8217;s nothing to tell you <em>what</em> went wrong. Specifically, I&#8217;ve wanted a way to report when the json parse fails.</p>
<p>Looking through the jQuery core, I found that the problem is that &#8220;status&#8221; field isn&#8217;t sent to the handler. A simple intervention on <code>jQuery.handleError</code> will close the gap:</p>
<pre>jQuery.handleErrorOriginal = $.handleError;
jQuery.handleError = function( s, xhr, status, e ){
  if (s.global) {
    xhr.error_status = status;
  }
  jQuery.handleErrorOriginal.apply(this, arguments);
};</pre>
<p>The &#8220;e&#8221; object is the original ajax configuration object. Since it reaches the global ajaxError listener, we can pull the status out of that.</p>
<p>Notice that I don&#8217;t <em>replace</em> the original functionality, I just do something before calling it with the same scope and arguments. The reason here is forwards-compatibility. Assuming that the name and api of jQuery.handleError doesn&#8217;t change, any changes to its internal functionality in future updates will likely be preserved without refactoring effort on your part.</p>
<p>To catch the errors:</p>
<pre>$("html").ajaxError(function(xhr, s, e){
    var msg;
    switch (s.error_status) {
      case "parsererror":
        msg = "A JSON parsing error occurred.";
        break;
      case "timeout":
        msg = "An ajax request timed out.";
        break;
      default:
        msg = "An ajax error occurred.";
        break;
    }
    alert(msg + "\n\n" + e.url);
});</pre>
<p>Why do I set <code>xhr.error_status</code> and then read <code>s.error_status</code>? Because, somewhere in the jumble of <code>handleError</code> and <code>trigger</code>, <code>xhr</code> becomes <code>s</code>. I love jQuery, but some of its core code can be quite difficult to read through.</p>
]]></content:encoded>
			<wfw:commentRss>http://emmett.be/thewebdev/archives/64/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>jQuery(document).ready() bug with Google Chrome 4.0 beta</title>
		<link>http://emmett.be/thewebdev/archives/46</link>
		<comments>http://emmett.be/thewebdev/archives/46#comments</comments>
		<pubDate>Thu, 19 Nov 2009 15:57:39 +0000</pubDate>
		<dc:creator>Emmett Pickerel</dc:creator>
				<category><![CDATA[Frontend]]></category>
		<category><![CDATA[bug]]></category>
		<category><![CDATA[google chrome]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://emmett.be/thewebdev/?p=46</guid>
		<description><![CDATA[I came across a major issue with jQuery (1.3.2) and Google Chrome 4.0 beta today. I&#8217;d been testing my company&#8217;s web application (for which I&#8217;m the primary frontend developer) with Chrome 3.0x, and it was working fine. After a sudden influx of chrome bug reports from someone using 4, I updated to that. And suddenly, ]]></description>
			<content:encoded><![CDATA[<p>I came across a major issue with jQuery (1.3.2) and Google Chrome 4.0 beta today. I&#8217;d been testing my company&#8217;s web application (for which I&#8217;m the primary frontend developer) with Chrome 3.0x, and it was working fine. After a sudden influx of chrome bug reports from someone using 4, I updated to that. And suddenly, nearly nothing worked.</p>
<p>After a fair bit of futzing around in my code and the <a href="http://code.google.com/p/jqueryjs/downloads/detail?name=jquery-1.3.2.js&amp;downloadBtn=" target="_blank">jQuery core library</a>, I discovered that in chrome 4 in certain cases (probably in large apps), the <code>DOMContentLoaded</code> event was never sent to the core jQuery library. To test this, I inserted a couple of lines into the file you saw above:</p>
<pre>3052  if ( document.addEventListener ) {
3053      // Use the handy event callback
<strong>[ins]     alert("jQ adding listener for DOMContentLoaded");</strong>
3054      document.addEventListener( "DOMContentLoaded", function(){
<strong>[ins]         alert("jQ received DOMContentLoaded event");</strong>
3055          document.removeEventListener( "DOMContentLoaded", arguments.callee, false );
3056          jQuery.ready();
3057      }, false );</pre>
<p>Both alerts show in FF, but only the first does in chrome. However, I found I <em>could</em> add my own and have them called.</p>
<p>Now, since the chances are you&#8217;re on this page because you googled for a workaround, here it is:</p>
<p><a href="http://emmett.be/thewebdev/wp-content/uploads/2009/11/jquery.chrome4fix.js">Google Chrome 4 beta jQuery document ready fix plugin</a></p>
<p>What this plugin does is first test to see if the browser is chrome 4, and if it is, then it adds another event listener for DOMContentLoaded, which will run even though the main jQuery one mysteriously does not. This calls jQuery.ready function (which is what is used to run through jQuery.readyList, the queued functions array).</p>
<p>We now have two chances for jQuery.ready to be called, therefore a potential race condition. To avoid this, I rewrote jQuery.ready() to null out  jQuery.readyList <em>before</em> cycling through the queued functions.</p>
<p>I still have no idea what&#8217;s causing Chrome 4 to fail on this. A test of document.readyState right after I added $(document).ready() shows that it is &#8220;loading&#8221;, so the problem isn&#8217;t that it finishes before adding the event handler or enqueueing the function.</p>
]]></content:encoded>
			<wfw:commentRss>http://emmett.be/thewebdev/archives/46/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>IE and newlines from innerHTML</title>
		<link>http://emmett.be/thewebdev/archives/33</link>
		<comments>http://emmett.be/thewebdev/archives/33#comments</comments>
		<pubDate>Sat, 28 Mar 2009 02:52:14 +0000</pubDate>
		<dc:creator>Emmett Pickerel</dc:creator>
				<category><![CDATA[Frontend]]></category>
		<category><![CDATA[ie bugs]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://emmett.be/thewebdev/?p=33</guid>
		<description><![CDATA[I ran into a problem today that I&#8217;m surprised I haven&#8217;t run into before. Internet Explorer loses newlines when pulling text from an HTML element. In short, if you use innerHTML, innerText or outerHTML on most elements, IE will convert newlines to spaces. Checking the charCodes of newlines (whether unix or ascii) shows them as ]]></description>
			<content:encoded><![CDATA[<p>I ran into a problem today that I&#8217;m surprised I haven&#8217;t run into before. Internet Explorer loses newlines when pulling text from an HTML element.</p>
<p>In short, if you use innerHTML, innerText or outerHTML on most elements, IE will convert newlines to spaces. Checking the charCodes of newlines (whether unix or ascii) shows them as 32s.</p>
<p>On the other hand, if I output (in a template) the text inside a PRE element, IE will keep the newlines. An element styled with white-space:pre won&#8217;t do the trick.</p>
<p>In my case, I have a TD and inner DIV which contain a text string. I need to show the full text string, with line breaks, in a popup dialog. (The CSS property white-space:pre isn&#8217;t useful, since long lines can&#8217;t wrap at all.) My two realistic options are to copy the data into a JS variable or put the text initially inside a PRE element.</p>
<p>Got to love Microsoft. They keep us webdevs in a job.</p>
]]></content:encoded>
			<wfw:commentRss>http://emmett.be/thewebdev/archives/33/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
