<?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>Quickduck &#187; Javascript</title> <atom:link href="http://quickduck.com/blog/category/javascript/feed/" rel="self" type="application/rss+xml" /><link>http://quickduck.com/blog</link> <description>Straight from the mind of geniuseseses....</description> <lastBuildDate>Mon, 09 Jan 2012 02:29:30 +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>What Is a Race Condition?</title><link>http://quickduck.com/blog/2009/10/06/what-is-a-race-condition/</link> <comments>http://quickduck.com/blog/2009/10/06/what-is-a-race-condition/#comments</comments> <pubDate>Tue, 06 Oct 2009 09:13:44 +0000</pubDate> <dc:creator>Drew Freyling</dc:creator> <category><![CDATA[.Net]]></category> <category><![CDATA[Asp.Net]]></category> <category><![CDATA[Javascript]]></category><guid isPermaLink="false">http://quickduck.com/blog/?p=188</guid> <description><![CDATA[Just thought I would put a post out on something I learnt today that can occur when using ajax- a race condition. A race condition is is where the output or result of something is dependent on the timing of other events/code. A good example of this is below: The problem here can occur when [...]]]></description> <content:encoded><![CDATA[<div class="google_plus_one"><g:plusone size="standard" count="false" url="http://quickduck.com/blog/2009/10/06/what-is-a-race-condition/"></g:plusone></div><p>Just thought I would put a post out on something I learnt today that can occur when using ajax- a race condition. A <a href="http://en.wikipedia.org/wiki/Race_condition" target="_blank">race condition</a> is is where the output or result of something is dependent on the timing of other events/code. A good example of this is below:</p><pre class="brush: jscript; title: ; notranslate">
function ValidateInput() {
//some slow running code here...
}

function SaveForm() {
//save the form
}
</pre><pre class="brush: xml; title: ; notranslate">

&lt;form&gt;
&lt;input type=&quot;text&quot; onchange=&quot;ValidateInput()&quot; /&gt;
&lt;input type=&quot;button&quot; onclick=&quot;SaveForm();&quot; value=&quot;Submit&quot; /&gt;
&lt;/form&gt;
</pre><p>The problem here can occur when the user hits the Submit button before the validation method can finish. One way to overcome this is use a <a title="Semaphore" href="http://en.wikipedia.org/wiki/Semaphore_%28programming%29" target="_blank">semaphore</a> to indicate whether the form still needs validating on the SaveForm method.</p> ]]></content:encoded> <wfw:commentRss>http://quickduck.com/blog/2009/10/06/what-is-a-race-condition/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Javascript &#8211; a quick reminder</title><link>http://quickduck.com/blog/2008/02/20/javascript-a-quick-reminder/</link> <comments>http://quickduck.com/blog/2008/02/20/javascript-a-quick-reminder/#comments</comments> <pubDate>Wed, 20 Feb 2008 16:58:02 +0000</pubDate> <dc:creator>Ben</dc:creator> <category><![CDATA[Development]]></category> <category><![CDATA[Javascript]]></category><guid isPermaLink="false">http://quickduck.com/blog/2008/02/20/javascript-a-quick-reminder/</guid> <description><![CDATA[My latest contract has seen my development time focus strongly on Sql Server, Xml and C# server side code. However, lately I&#8217;ve been playing around with all the new Asp.Net 3.5 extensions (MVC) and Linq with VS 2008 and found that I could use a refresher course in all things Javascript &#8211; particularly Ajax and [...]]]></description> <content:encoded><![CDATA[<div class="google_plus_one"><g:plusone size="standard" count="false" url="http://quickduck.com/blog/2008/02/20/javascript-a-quick-reminder/"></g:plusone></div><p>My latest contract has seen my development time focus strongly on Sql Server, Xml and C# server side code.</p><p>However, lately I&#8217;ve been playing around with all the new Asp.Net 3.5 extensions (MVC) and Linq with VS 2008 and found that I could use a refresher course in all things Javascript &#8211; particularly Ajax and JSON.</p><p>I found this awesome <a href="http://www.sergiopereira.com/articles/advjs.html">guide</a> which gives you a quick reminder of the useful techniques required to author some top notch client side code when building web apps.</p> ]]></content:encoded> <wfw:commentRss>http://quickduck.com/blog/2008/02/20/javascript-a-quick-reminder/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>ibox, Prototype, and JSON</title><link>http://quickduck.com/blog/2007/08/02/ibox-prototype-and-json/</link> <comments>http://quickduck.com/blog/2007/08/02/ibox-prototype-and-json/#comments</comments> <pubDate>Thu, 02 Aug 2007 08:26:23 +0000</pubDate> <dc:creator>Gerrod</dc:creator> <category><![CDATA[Asp.Net]]></category> <category><![CDATA[C#]]></category> <category><![CDATA[Javascript]]></category><guid isPermaLink="false">http://quickduck.com/blog/?p=38</guid> <description><![CDATA[In my current project, I&#8217;m doing some fancy-pants stuff to lookup UK addresses via a web service, then send them to the client using JSON. On the client end, I&#8217;m displaying the results in an ibox and then sending the results back to the main form. Woah! The first challenge was getting the ibox to [...]]]></description> <content:encoded><![CDATA[<div class="google_plus_one"><g:plusone size="standard" count="false" url="http://quickduck.com/blog/2007/08/02/ibox-prototype-and-json/"></g:plusone></div><p>In my current project, I&#8217;m doing some fancy-pants stuff to lookup UK addresses via a web service, then send them to the client using JSON. On the client end, I&#8217;m displaying the results in an <a href="http://www.ibegin.com/blog/p_ibox.html" target="_blank">ibox</a> and then sending the results back to the main form. Woah!</p><p>The first challenge was getting the ibox to open and display the form correctly. I chose to use a hidden div as my &#8220;form&#8221;, and let the ibox display it on the screen when appropriate. It all seemed to work correctly, however when I tried to read the values out of the fields on the ibox form, it kept telling me they were empty!</p><p>After a lot of mucking around, cursing, and rude gestures directed at the computer &#8211; you know, the standard debugging drill &#8211; I worked out that when you use a hidden div as your ibox, it actually *clones* the entire InnerHTML of the hidden div! So in effect, you get *two* of every field with duplicate IDs. And, since the HTML generated by ibox goes at the *end* of your document, when you call document.getElementById, you get back the *first matching element*, which will always be the one that&#8217;s still safely hidden away in your form. Handy &#8211; not!!</p><p>But never fear, the solution is actually quite simple. You just have to create an external file containing your ibox form, and then use that as the HREF in your link:</p><pre><code>
&lt;a href="FindAddress.aspx" rel="ibox&#038;height=400" title="Find an address"&gt;Find address&lt;/a&gt;
</code></pre><p>Ahh, finally things started working properly! So now that I could read the postcode that the user entered, I wanted to hit a handler to&#8230;. err&#8230; &#8220;handle&#8221; the web service request. To do that, I used <a href="http://www.prototypejs.org/" target="_blank">prototype.js</a> &#8211; a javascript library with a whole bunch of wicked cool functionality (all of which is way beyond the scope of this article). Check it out -to execute a cross browser friendly AJAX request, you simply do this:</p><pre><code>
  var url = "Handlers/FindAddressHandler.ashx?Id=" + id;
  new Ajax.Request(url, {
    onSuccess: OnAddressFound,
    onFailure: OnError
  });
</code></pre><p>Of course, you can inline the callback functions, but I wanted to separate them for readability. Anyway, the next part was setting up the FindAddressHandler. I won&#8217;t go into too much detail here as it&#8217;s just a standard implementation of IHttpHandler which then hits a web service. The part I want to talk about though is writing back the address object using JSON. A dude named Jason Newton King has written a brilliant library called <a href="http://www.newtonsoft.com/blog/archive/2006/06/26/571.aspx" target="_blank">Json.NET</a> which makes life a hell of a lot easier!<p>Basically, you just have to create a JsonWriter, then serialise the properties of your object that you want to send back to the client. So in my case with an Address object (stored in local variable &#8220;address&#8221;):</p><pre><code>
StringBuilder builder = new StringBuilder();
using (JsonWriter writer = new JsonWriter(new StringWriter(builder))) {
  writer.WriteStartObject();
  writer.WritePropertyName("PostCode");
  writer.WriteValue(address.Postcode);
  writer.WritePropertyName("Address1");
  writer.WriteValue(address.Line1);
  writer.WritePropertyName("Address2");
  writer.WriteValue(address.Line2);
  writer.WritePropertyName("Address3");
  writer.WriteValue(address.Line3);
  writer.WritePropertyName("PostalTown");
  writer.WriteValue(address.PostTown);
  writer.WriteEndObject();

  writer.Flush();
}

_context.Response.AddHeader("X-JSON", builder.ToString());
</code></pre><p>Easy, right? So the thing to note here, besides how simple it is to persist your object in JSON, is that I&#8217;m sending back the JSON string in a response header called &#8220;X-JSON&#8221;. Now back on the client side again &#8211; one of the bonus features of Prototype is that it automatically interprets whatever is in the &#8220;X-JSON&#8221; header, and builds your objects for you! So, here&#8217;s the code I wrote for my client-side callback:</p><pre><code>
function OnAddressFound(transport, address) {
    $("txtAddress1").value = address.Address1;
    $("txtAddress2").value = address.Address2;
    $("txtAddress3").value = address.Address3;
    $("txtPostCode").value = address.PostCode;
    $("txtPostalTown").value = address.PostalTown;

    hideIbox();
}
</code></pre><p>The first argument &#8211; transport &#8211; is the XmlHttpRequest object which was used. (You can find a great document which outlines the properties of the XmlHttpRequest object on the <a href="http://developer.apple.com/internet/webcontent/xmlhttpreq.html" target="_blank">Apple Developer Connection</a> website). The second argument is the object which Prototype interpreted from the X-JSON response header. You can see also that prototype implements a function &#8211; $ &#8211; which is effectively a suped-up version of document.getElementById.</p><p> Using all of these technologies together was surprisingly easy! I&#8217;m super impressed with how you can grab so many rich frameworks to enhance your websites, all for free!</p> ]]></content:encoded> <wfw:commentRss>http://quickduck.com/blog/2007/08/02/ibox-prototype-and-json/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Internet Explorer script tag failure for valid xhtml</title><link>http://quickduck.com/blog/2007/01/11/internet-explorer-script-tag-failure-for-valid-xhtml/</link> <comments>http://quickduck.com/blog/2007/01/11/internet-explorer-script-tag-failure-for-valid-xhtml/#comments</comments> <pubDate>Thu, 11 Jan 2007 14:54:29 +0000</pubDate> <dc:creator>Ben</dc:creator> <category><![CDATA[.Net]]></category> <category><![CDATA[Asp.Net]]></category> <category><![CDATA[Javascript]]></category><guid isPermaLink="false">http://quickduck.com/blog/?p=18</guid> <description><![CDATA[Boy, what a day! I was working on the weirdest bug with a colleague today where we were receiving a javascript &#8220;Object expected&#8221; error when we migrated a page into our new ASP .Net Master Page format. We thought we hadn&#8217;t made any breaking changes, all we had done was move the &#60;script&#62; tags into [...]]]></description> <content:encoded><![CDATA[<div class="google_plus_one"><g:plusone size="standard" count="false" url="http://quickduck.com/blog/2007/01/11/internet-explorer-script-tag-failure-for-valid-xhtml/"></g:plusone></div><p>Boy, what a day!</p><p>I was working on the weirdest bug with a colleague today where we were receiving a javascript &#8220;Object expected&#8221; error when we migrated a page into our new ASP .Net Master Page format.</p><p>We thought we hadn&#8217;t made any breaking changes, all we had done was move the &lt;script&gt; tags into the MasterPage file from the content page.</p><p>That didn&#8217;t work, so we created a header content place holder in the master page &lt;head&gt; element and in the content page put back the &lt;script&gt; includes. That didn&#8217;t work either.</p><p>We then included the &lt;script&gt; tags in both the master and content page. That seemed to work. Very odd.</p><p>In the end after many attempts to figure out what was going wrong, we found the problem was with how MSIE parses &lt;script&gt; tags, it cannot use self closing tags or an empty element &#8211; ie. &lt;script &#8230; /&gt;.</p><p>It <strong>has</strong> to have the &lt;script>&lt;/script&gt; tag.</p><p>For more info check out <a href="http://www.quirksmode.org/bugreports/archives/2006/06/MSIE_script_tag_failure_in_valid_xhtml.html" target="_blank">quirksmode.org</a>.</p> ]]></content:encoded> <wfw:commentRss>http://quickduck.com/blog/2007/01/11/internet-explorer-script-tag-failure-for-valid-xhtml/feed/</wfw:commentRss> <slash:comments>1</slash:comments> </item> <item><title>Javascript &#8211; Inheritance</title><link>http://quickduck.com/blog/2006/12/05/javascript-inheritance/</link> <comments>http://quickduck.com/blog/2006/12/05/javascript-inheritance/#comments</comments> <pubDate>Tue, 05 Dec 2006 10:56:56 +0000</pubDate> <dc:creator>Ben</dc:creator> <category><![CDATA[Development]]></category> <category><![CDATA[Javascript]]></category><guid isPermaLink="false">http://quickduck.com/blog/?p=10</guid> <description><![CDATA[There are many ways to perform inheritance using objects in javascript. I recommend reading chapter 3 and 4 from Professional Javascript for Web Developers&#8221; to get a full understanding of how the language can be utilized for inheritance. Below I have listed a hybrid method that incorporates using the call() method and prototype chaining to [...]]]></description> <content:encoded><![CDATA[<div class="google_plus_one"><g:plusone size="standard" count="false" url="http://quickduck.com/blog/2006/12/05/javascript-inheritance/"></g:plusone></div><p>There are many ways to perform inheritance using objects in javascript. I recommend reading chapter 3 and 4 from <a href="http://www.amazon.com/Professional-JavaScript-Developers-Wrox-Guides/dp/0764579088/sr=8-1/qid=1165316198/ref=pd_bbs_sr_1/002-0435302-7045655?ie=UTF8&#038;s=books" target="_blank">Professional Javascript for Web Developers&#8221;</a> to get a full understanding of how the language can be utilized for inheritance.</p><p>Below I have listed a hybrid method that incorporates using the call() method and prototype chaining to simulate inheritance that matches closely to how you would use it in a typed language like Java or C#.</p><pre><code>

function File(name, path) {
	this.name = name;
	this.path = path;
}

File.prototype.getName = function() { return this.name; }
File.prototype.setName = function(name) { this.name = name; }

File.prototype.getPath = function() { return this.path; }
File.prototype.setPath = function(path) { this.path = path; }

</code>
</pre><p>Using the prototype keyword, means that the method is assigned to the File class. Without it, the function would be a new instance for every instantiated File object.</p><p>The following subclass utilizes the call() method which in this case is analogous to the super keyword in java or the base keyword in C#.</p><p>It then uses prototype chaining to assign/copy all the prototype functions of File to itself, <strong>before</strong> defining further functions that relate specifically to itself.</p><pre><code>
function ExcelFile(name, path, numberOfWorksheets) {
	File.call(this, name, path); // equivalent to calling base(name, path)
        this.numberOfWorksheets = numberOfWorksheets;
}

// this is how you inherit all the prototype values of the base class.
// ensure to place this before defining new functions as this will blat out
// all prototype functions currently declared for the class.
ExcelFile.prototype = new File(); 

ExcelFile.prototype.getNumberOfWorksheets =
	function() { return this.numberOfWorksheets; }

ExcelFile.prototype.setNumberOfWorksheets =
	function(numberOfWorksheets) { this.numberOfWorksheets =
							numberOfWorksheets; }

</code>
</pre><p>The following shows how you would instantiate your classes and prove that the inheritance worked.</p><pre><code>
var file = new File("RecipeDetails.txt", "c:/temp");
var excelFile = new ExcelFile("Business.xls", "c:/temp", 6);

alert(excelFile instanceof File);
alert(excelFile instanceof ExcelFile);
</code></pre>]]></content:encoded> <wfw:commentRss>http://quickduck.com/blog/2006/12/05/javascript-inheritance/feed/</wfw:commentRss> <slash:comments>1</slash:comments> </item> <item><title>function $</title><link>http://quickduck.com/blog/2006/11/16/function/</link> <comments>http://quickduck.com/blog/2006/11/16/function/#comments</comments> <pubDate>Thu, 16 Nov 2006 22:11:41 +0000</pubDate> <dc:creator>Gerrod</dc:creator> <category><![CDATA[Asp.Net]]></category> <category><![CDATA[Javascript]]></category><guid isPermaLink="false">http://quickduck.com/blog/?p=4</guid> <description><![CDATA[A while back, Bender sent me a link to a prototype.js file that pretty much claimed to be a web developers best friend. It certainly has some interesting features, and one that I really liked was the &#8220;$&#8221; function. Basically, the developer had written the function to return you an array of the elements that [...]]]></description> <content:encoded><![CDATA[<div class="google_plus_one"><g:plusone size="standard" count="false" url="http://quickduck.com/blog/2006/11/16/function/"></g:plusone></div><p>A while back, Bender sent me a link to a <a href="http://prototype.conio.net/dist/prototype-1.4.0.js">prototype.js file</a> that pretty much claimed to be a web developers best friend. It certainly has some interesting features, and one that I really liked was the &#8220;$&#8221; function. Basically, the developer had written the function to return you an array of the elements that you asked for by id. So in effect, if you wrote -</p><p><code>var elements = $("txtName", "txtPhone", "txtCountry");</code></p><p>- then you would be returned an array containing a reference to each of those form elements (presuming that they exist, of course ;-))</p><p>Well that&#8217;s all fine and dandy, but more often than not I find myself trying to find elements in that are declared as: runat=&#8221;server&#8221;. And if those elements are nested in a UserControl, then you have to know how their id will be transformed at runtime by ASP.NET (for example, &#8220;txtName&#8221; may become &#8220;ctl00_main_sidebar_txtName&#8221;). So, with this in mind, I wrote my own version of the $ function which took care of this situation for me:</p><pre><code>
/*
 * Find an element based on the provided strings
 *
 * elementId:   Server-side id of the element to find (e.g. "txtName")
 * tagName:     The runtime tag of the element (e.g. "input")
 * elementType: The runtime value of the "type" attribute for the element,
 *              if it exists (e.g. "text")
 */
function $(elementId, tagName, elementType) {
    if (!tagName || tagName == "") {
        return document.getElementById(elementId);

    } else if (tagName) {
        var elements = document.getElementsByTagName(tagName, "gi");
        var typeRegex = elementType &#038;&#038; elementType != "" ? new RegExp(elementType) : null;

        for (var i = 0; i < elements.length; i++) {
            if (typeRegex) {
                if (!elements[i].type || !typeRegex.exec(elements[i].type)) {
                    continue;
                }
            }

            if (elements[i].id &#038;&#038; elements[i].id.indexOf(elementId) >= 0) {
                return elements[i];
            }
        }
    }

    return null;
}
</code></pre><p>It&#8217;s possibly not <i>the</i> most efficient piece of code that you&#8217;ll ever come across, but it does the job perfectly.</p> ]]></content:encoded> <wfw:commentRss>http://quickduck.com/blog/2006/11/16/function/feed/</wfw:commentRss> <slash:comments>1</slash:comments> </item> </channel> </rss>
<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Minified using disk: basic
Page Caching using disk: enhanced

Served from: quickduck.com @ 2012-02-05 16:42:31 -->
