<?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>Just another WordPress site</title>
	<atom:link href="http://blog.nemikor.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.nemikor.com</link>
	<description>Just another WordPress site</description>
	<lastBuildDate>Thu, 04 Jun 2015 14:56:24 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>
	<item>
		<title>Controlling an Off-the-Shelf RC Car with an Arduino</title>
		<link>http://blog.nemikor.com/2015/06/04/controlling-an-off-the-shelf-rc-car-with-an-arduino/</link>
		
		<dc:creator><![CDATA[Scott GonzÃ¡lez]]></dc:creator>
		<pubDate>Thu, 04 Jun 2015 14:55:53 +0000</pubDate>
				<category><![CDATA[Arduino]]></category>
		<category><![CDATA[Johnny-Five]]></category>
		<category><![CDATA[Node.js]]></category>
		<guid isPermaLink="false">http://blog.nemikor.com/?p=106</guid>

					<description><![CDATA[Last month I bought my first Arduino (actually a SparkFun RedBoard) and started playing around with Johnny-Five to control it via JavaScript. Since then, I&#8217;ve learned the basics of electronics, microcontrollers, and how Johnny-Five works. This weekend, I decided to buy a cheap RC car and see if I could hack the remote so I&#8230; <a class="more-link" href="http://blog.nemikor.com/2015/06/04/controlling-an-off-the-shelf-rc-car-with-an-arduino/">Continue reading <span class="screen-reader-text">Controlling an Off-the-Shelf RC Car with an Arduino</span></a>]]></description>
										<content:encoded><![CDATA[<p>Last month I bought my first Arduino (actually a <a href="https://www.sparkfun.com/products/12757">SparkFun RedBoard</a>) and started playing around with <a href="http://johnny-five.io/">Johnny-Five</a> to control it via JavaScript. Since then, I&#8217;ve learned the basics of electronics, microcontrollers, and how Johnny-Five works. This weekend, I decided to buy a cheap RC car and see if I could hack the remote so I could control the car with my laptop.</p>
<p>I picked up a <a href="http://newbright.com/rccar/2424-silverado-rc-trucks/">1/24 scale New Bright 2014 Silverado</a> for about $10 at Target. I chose this model because of the truck bed, so I would have a place to mount a microcontroller in case I decided to mod the car itself later. I also made sure to check what kind of batteries the remote used to make sure I could power it from my RedBoard. The remote uses two AAs, which is a total of 3 volts, so I figured the 3.3v power pin would be perfect. The car itself uses three AAs, which is a total of 4.5 volts, so if I do go down the road of hacking the car, using the 5v power pin should be fine.</p>
<p><a href="http://blog.nemikor.com/wp-content/uploads/remote-original.jpg"><img fetchpriority="high" decoding="async" class="size-medium wp-image-111 aligncenter" alt="unmodified remote" src="http://blog.nemikor.com/wp-content/uploads/remote-original-300x200.jpg" width="300" height="200" srcset="http://blog.nemikor.com/wp-content/uploads/remote-original-300x200.jpg 300w, http://blog.nemikor.com/wp-content/uploads/remote-original-1024x682.jpg 1024w, http://blog.nemikor.com/wp-content/uploads/remote-original.jpg 1200w" sizes="(max-width: 300px) 100vw, 300px" /></a></p>
<p>The first thing I do whenever I dig into anything new is making sure that it works as I expect, so I can verify the behavior is the same after every step. After my kids played with the car for a bit, I knew everything was working, so it was time to start ripping things apart. The remote was just two pieces of plastic held together with two screws and a few plastic clips. As soon as I opened it, I found something unexpected. The joysticks were actually just two buttons for each axis, not a standard joystick with variable movement along the axes. In hindsight, this should have been obvious since the car didn&#8217;t have variable speed and the wheels snapped to a specific position when turning.</p>
<p><a href="http://blog.nemikor.com/wp-content/uploads/remote-open.jpg"><img decoding="async" class="size-medium wp-image-110 aligncenter" alt="remote opened up" src="http://blog.nemikor.com/wp-content/uploads/remote-open-300x200.jpg" width="300" height="200" srcset="http://blog.nemikor.com/wp-content/uploads/remote-open-300x200.jpg 300w, http://blog.nemikor.com/wp-content/uploads/remote-open-1024x682.jpg 1024w, http://blog.nemikor.com/wp-content/uploads/remote-open.jpg 1200w" sizes="(max-width: 300px) 100vw, 300px" /></a></p>
<p>Now that I had the remote opened up, I had to get the circuit board out of the plastic. This was just a matter of pulling the battery leads straight out (while compressing the spring for the negative lead), then the circuit board came out very easily. I used some jumper wires to connect the 3.3v and GND pins from the Arduino to the battery contacts and pushed the forward button to make sure powering the remote was going to work. Once I had confirmed this worked, I hooked up two AAs so that I didn&#8217;t need to hold the wires in place as I did more testing. I then tested all four buttons just to make sure everything was still working.</p>
<p><a href="http://blog.nemikor.com/wp-content/uploads/existing-battery-leads.jpg"><img decoding="async" class="size-medium wp-image-113 aligncenter" alt="The existing battery leads in the remote. The spring for the negative lead needs to be compressed to pull out the circuit board." src="http://blog.nemikor.com/wp-content/uploads/existing-battery-leads-300x200.jpg" width="300" height="200" srcset="http://blog.nemikor.com/wp-content/uploads/existing-battery-leads-300x200.jpg 300w, http://blog.nemikor.com/wp-content/uploads/existing-battery-leads-1024x682.jpg 1024w, http://blog.nemikor.com/wp-content/uploads/existing-battery-leads.jpg 1200w" sizes="(max-width: 300px) 100vw, 300px" /></a></p>
<p><a href="http://blog.nemikor.com/wp-content/uploads/battery-holder.jpg"><img loading="lazy" decoding="async" class="size-medium wp-image-114 aligncenter" alt="battery-holder" src="http://blog.nemikor.com/wp-content/uploads/battery-holder-300x200.jpg" width="300" height="200" srcset="http://blog.nemikor.com/wp-content/uploads/battery-holder-300x200.jpg 300w, http://blog.nemikor.com/wp-content/uploads/battery-holder-1024x682.jpg 1024w, http://blog.nemikor.com/wp-content/uploads/battery-holder.jpg 1200w" sizes="auto, (max-width: 300px) 100vw, 300px" /></a></p>
<p>At this point, my plan was to replace the buttons with some other component that I could control from the Arduino. I wasn&#8217;t really sure what I could use for the replacement though. My only thought was to use a relay, but then I decided to try to trace the circuit and see if there was another way to hook in without desoldering the buttons. I noticed that there were seemingly random solder points connected to each of the buttons (these turned out to be test points for the board), so I decided to try applying voltage to the solder point for the forward button. I already had a script open that blinks an LED every second, so I just used that for my testing, since it would toggle between a HIGH and LOW signal on the pin. I was happy to find out that this worked (once I remembered to connect the GND pin as well to complete the circuit). I then tested the other three solder points to make sure I had identified the correct point for each button.</p>
<p>I was finally ready to start modifying the board. I plugged in my soldering iron and cut six pieces of hookup wire (one for each button and two for power) while the iron was heating up. First up was desoldering the battery leads and adding the new wire leads to connect to the Arduino. Then I soldered a wire to each of the four solder points that corresponded to the four buttons. This is where I made my biggest mistake. I didn&#8217;t realize how stiff the hookup wire was and how fragile the solder points would be. When I tried to bend all the wires to plug into my breadboard, I ended up ripping out the wire for reverse. I had to solder the wire directly to the button at that point, but I learned a valuable lesson: bend the wires into their desired shape prior to soldering.</p>
<p><a href="http://blog.nemikor.com/wp-content/uploads/completed-project.jpg"><img loading="lazy" decoding="async" class="size-medium wp-image-115 aligncenter" alt="The circuit board with new leads, connected to a breadboard." src="http://blog.nemikor.com/wp-content/uploads/completed-project-300x200.jpg" width="300" height="200" srcset="http://blog.nemikor.com/wp-content/uploads/completed-project-300x200.jpg 300w, http://blog.nemikor.com/wp-content/uploads/completed-project-1024x682.jpg 1024w, http://blog.nemikor.com/wp-content/uploads/completed-project.jpg 1200w" sizes="auto, (max-width: 300px) 100vw, 300px" /></a></p>
<p>Now that the board was modified, I was ready to write a script to control the car. I decided to keep it simple and just use the arrow keys. Rather than having to hold down the keys, I made each action &#8220;sticky&#8221; so pressing up once would make the car go forward until you either pressed up again to stop it or pressed down to make it go in reverse. This worked pretty well, but it was very awkward for turning. Modifying the script to treat left and right as momentary actions would make it easier to control. My next step will probably be exposing the controls via a web server so my kids can control the car with their iPads. I never thought I&#8217;d be able to do that with a cheap off-the-shelf RC car and just an hour or two of tinkering. After just a few weeks of playing with Johnny-Five, it all seems so simple <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<pre class="lang:javascript">
var five = require("johnny-five");
var keypress = require("keypress");

keypress(process.stdin);
process.stdin.resume();

var board = new five.Board();

board.on("ready", function() {
	var forward = new five.Led(13);
	var back = new five.Led(7);
	var left = new five.Led(12);
	var right = new five.Led(8);

	forward.on();
	back.on();
	left.on();
	right.on();

	process.stdin.on("keypress", function(_, key) {
		if (!key) {
			return;
		}

		switch (key.name) {
			case "up":
				forward.toggle();
				back.on();
				break;

			case "down":
				back.toggle();
				forward.on();
				break;

			case "left":
				left.toggle();
				right.on();
				break;

			case "right":
				right.toggle();
				left.on();
				break;

			case "c":
				if (key.ctrl) {
					process.exit();
				}
				break;
		}
	});

	this.repl.inject({
		forward: forward,
		back: back,
		left: left,
		right: right
	});
});
</pre>
<p class="note"><strong>Note:</strong> This script uses the <a href="https://www.npmjs.com/package/keypress">keypress</a> module.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Blissful Testing of Locally Hosted Sites</title>
		<link>http://blog.nemikor.com/2013/12/06/blissful-testing-of-locally-hosted-sites/</link>
		
		<dc:creator><![CDATA[Scott GonzÃ¡lez]]></dc:creator>
		<pubDate>Fri, 06 Dec 2013 22:08:34 +0000</pubDate>
				<category><![CDATA[Apache]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[physical device]]></category>
		<category><![CDATA[web server]]></category>
		<guid isPermaLink="false">http://blog.nemikor.com/?p=95</guid>

					<description><![CDATA[When I first started using a web server on my local machine for development, I used to create a separate virtual host for every site I worked on. Then I learned that you can use a ServerAlias with a wildcard to handle multiple sites with a single virtual host. Since then, I&#8217;ve been using the&#8230; <a class="more-link" href="http://blog.nemikor.com/2013/12/06/blissful-testing-of-locally-hosted-sites/">Continue reading <span class="screen-reader-text">Blissful Testing of Locally Hosted Sites</span></a>]]></description>
										<content:encoded><![CDATA[<p>When I first started using a web server on my local machine for development, I used to create a separate virtual host for every site I worked on. Then I learned that you can use a <a href="http://httpd.apache.org/docs/2.2/mod/core.html#serveralias">ServerAlias</a> with a wildcard to handle multiple sites with a single virtual host. Since then, I&#8217;ve been using the following simple configuration to test most of my projects:</p>
<pre class="lang:apache">
<VirtualHost *>
	ServerName tmp.code.dev
	ServerAlias *.code.dev
	VirtualDocumentRoot /path/to/projects/%1
	<Directory />
		AllowOverride All
	</Directory>
</VirtualHost>
</pre>
<p>This tells Apache that any domain ending with <code>.code.dev</code> should be served by the directory in <code>/path/to/projects/</code> that has the same name as the beginning of the domain. For example, <code>foo.code.dev</code> would be served from <code>/path/to/projects/foo/</code>. This reduces my per-project setup to just adding an entry in <code>/etc/hosts</code> to map the custom domain to my local machine, e.g., <code>127.0.0.1 foo.code.dev</code>. Unfortunately, wildcards can&#8217;t be used in the hosts file, so this step needs to occur for every project. That&#8217;s a little annoying, but it&#8217;s easy enough that I was willing to live with it.</p>
<p>As I started working on more sites (as opposed to libraries or frameworks that happen to need a web server), I created another VirtualHost to create nicer domains and handle subdomains. If I&#8217;m working on <code>foo.com</code>, I create a directory named <code>/foo.com/</code> in my projects directory and use the domain <code>local-dev.foo.com</code> for testing.</p>
<pre class="lang:apache">
<VirtualHost *>
	ServerName local-dev
	ServerAlias local-dev.*
	VirtualDocumentRoot /path/to/projects/%2+
	<Directory />
		AllowOverride All
	</Directory>
</VirtualHost>
</pre>
<p>Using <code>%2+</code> tells Apache to use every part of the domain after the first part. You can read more about how the <code>VirtualDocumentRoot</code> interpolation works in the <a href="http://httpd.apache.org/docs/2.2/mod/mod_vhost_alias.html"><code>mode_vhost_alias</code> documentation</a>. And of course, I would add <code>127.0.0.1 local-dev.foo.com</code> to my hosts file.</p>
<h3>Testing from physical devices</h3>
<p>Unfortunately, there is a big limitation to this setup. When testing from a physical device, such as a phone or tablet, the custom domain won&#8217;t map to your local web server. Since the physical device doesn&#8217;t know anything about the hosts file on the machine with the web server, trying to load <code>foo.code.dev</code> from the device&#8217;s browser isn&#8217;t going to work. This generally discouraged me from testing on physical devices because I never had a great solution to this problem. Whenever the need would arise, I&#8217;d create another virtual host using my machine&#8217;s LAN IP and a random port:</p>
<pre class="lang:apache">
<VirtualHost 192.168.1.2:1234>
	ServerName local-dev.foo.com
	DocumentRoot /path/to/projects/foo.com
	<Directory />
		AllowOverride All
	</Directory>
</VirtualHost>
</pre>
<p>Then I can connect to <code>192.168.1.2:1234</code> instead of <code>local-dev.foo.com</code> from any physical device connected to my network. But I&#8217;ve lost the benefit of the wildcard aliasing and now I need to remember which port to use. This can be quite burdensome as the number of sites increases, especially since each site needs to use a different port.</p>
<p>After years of dealing with this, I decided to <a href="http://twitter.com/scott_gonzalez/status/408604075065110528">ask for help on Twitter</a>. I got a few responses, but the one I like the best came from <a href="http://www.andrewsheppard.net/">Andrew Sheppard</a>, who pointed me to <a href="http://xip.io">xip.io</a>.</p>
<h3>xip.io to the rescue</h3>
<p><a href="http://xip.io">xip.io</a> is a free service from <a href="http://37signals.com/">37signals</a>, which provides wildcard DNS for any IP address. Just like we can map <code>*.code.dev</code> to the appropriate directory on our local machine, xip.io can map <code>*.xip.io</code> to the appropriate IP for local testing. The URL structure is nice and simple, just prepend the IP address you want the domain to resolve to; the xip.io DNS server handles the rest. In this case, we&#8217;d use <code>192.168.1.2.xip.io</code> to map the domain to <code>192.168.1.2</code>.</p>
<p>This solves the DNS issue and removes the need to edit the hosts file for each site. But given a domain of <code>192.168.1.2.xip.io</code>, we still don&#8217;t know which directory to server the site from. To address this, xip.io allows adding as many subdomains as you want. So we can use <code>foo.com.192.168.1.2.xip.io</code> and then create a virtual host that knows how to handle xip.io domains.</p>
<pre class="lang:apache">
<VirtualHost *>
	ServerName xip
	ServerAlias *.xip.io
	VirtualDocumentRoot /path/to/projects/%-7+
	<Directory />
		AllowOverride All
	</Directory>
</VirtualHost>
</pre>
<h3>Handling DNS on your local machine</h3>
<p>Although the xip.io setup does allow for zero-configuration setup, there are a few caveats.</p>
<p><strong>The URLs are long and a bit ugly.</strong> I&#8217;ve created a simple page, <a href="http://bit.ly/xipio">bit.ly/xipio</a>, to generate the xip.io URLs so I don&#8217;t need to type the full URL in the tiny address bar on my devices. I also kept my <code>local-dev.*</code> virtual host enabled so that I can use shorter, nicer URLs if I want, though this does require adding an entry in the hosts file as mentioned above, and doesn&#8217;t allow testing from physical devices. </p>
<p><strong>The URLs don&#8217;t work offline.</strong> Obviously if you can&#8217;t can&#8217;t connect to xip.io, the whole thing is going to fall apart.</p>
<p><strong>The URLs aren&#8217;t shareable.</strong> Since the domain contains your personal LAN IP, sharing links with other developers working on the same site from <em>their</em> local machine won&#8217;t work (unless you happen to have the same LAN IP). However, it&#8217;s quite easy for the other person to change the IP after you&#8217;ve shared it with them.</p>
<h3>More on link sharing</h3>
<p>Link sharing is really useful when working on a project with other people, so it&#8217;s worth discussing specifically. As I mentioned above, while xip.io URLs can&#8217;t just be copy/pasted, they&#8217;re fairly easy to work with. However, having a common setup, such as <code>local-dev.*</code> for your projects makes link sharing much easier. If everyone working on the project is using <code>local-dev.foo.com</code> when testing from the main machine, then link sharing just works.</p>
<p>To avoid having everyone edit their hosts file to get the domain mapping to work, another option is to actually create a DNS record for <code>local-dev.foo.com</code>. By creating an A record that points <code>local-dev.foo.com</code> to <code>127.0.0.1</code>, you can get back to a zero-configuration setup. However, you do have the same offline problem as using xip.io, but that can be solved via the hosts file for any developer that needs offline access to work.</p>
<h3>Other solutions</h3>
<p>As with most things related to software development, there&#8217;s more than one solution to this problem. <a href="http://mattsurabian.com">Matt Surabian</a> wrote an article about <a href="http://mattsurabian.github.io/how-i-test-locally-hosted-sites-with-physical-devices/">using Charles Proxy to test local sites with physical devices</a> in response to my tweet. Using <a href="http://www.charlesproxy.com/">Charles Proxy</a> has a different set of pros and cons, so I suggest reading Matt&#8217;s article and determining which solution works best for you.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Creating Application-specific jQuery plugins</title>
		<link>http://blog.nemikor.com/2010/08/16/creating-application-specific-jquery-plugins/</link>
		
		<dc:creator><![CDATA[Scott GonzÃ¡lez]]></dc:creator>
		<pubDate>Tue, 17 Aug 2010 00:25:30 +0000</pubDate>
				<category><![CDATA[jQuery]]></category>
		<category><![CDATA[namespace]]></category>
		<category><![CDATA[plugin]]></category>
		<guid isPermaLink="false">http://blog.nemikor.com/?p=81</guid>

					<description><![CDATA[When building an application with jQuery, it&#8217;s very likely that you will end up writing some code that would be easiest to use directly in a jQuery chain. When the functions you&#8217;re writing solve general problems that don&#8217;t have a dependency on your application, it&#8217;s usually obvious that you should write the function as a&#8230; <a class="more-link" href="http://blog.nemikor.com/2010/08/16/creating-application-specific-jquery-plugins/">Continue reading <span class="screen-reader-text">Creating Application-specific jQuery plugins</span></a>]]></description>
										<content:encoded><![CDATA[<p>When building an application with jQuery, it&#8217;s very likely that you will end up writing some code that would be easiest to use directly in a jQuery chain. When the functions you&#8217;re writing solve general problems that don&#8217;t have a dependency on your application, it&#8217;s usually obvious that you should write the function as a jQuery plugin. However, when you&#8217;re writing code that is very specific to your application and you want to use it in a chain, it&#8217;s not always clear whether writing the function as a jQuery plugin is a good idea.</p>
<p>I&#8217;ve come across three main categories of application-specific plugins since I started using jQuery. The first category contains plugins that are useful throughout most of your application, but useless outside of your application. These plugins usually deal with traversing and manipulating common components based on specific markup in your application. This set of plugins can be used on many elements across many pages and therefore get the most reuse. The second category contains plugins that are tied to a specific element that persists across most, if not all, of your application. These are different from the first category because the plugins are never called on more than one element for any page load. You can think of these as Singleton DOM components, such as help dialogs. The final category consists of plugins that are only used on a single page. In many cases these plugins will be used on multiple elements within the page, but the plugin is never loaded on any other page.</p>
<p>One pattern for creating application-specific plugins is to prefix your method names to prevent name collisions. For example, let&#8217;s say we have lots of widgets with common markup structures. If we want to be able to navigate from any given element on the page to the widget the element is contained in, we might create a method called <code>nmkWidget</code>.</p>
<p>Let&#8217;s assume the widgets have the following shell:</p>
<pre class="lang:html">
<div class="nmk-widget">
	<div class="nmk-widget-header">
		<!-- widget-specific header -->
	</div>
	<div class="nmk-widget-content">
		<!-- widget-specific content -->
	</div>
</div>
</pre>
<p>We can define some helper functions for navigating the DOM:</p>
<pre class="lang:javascript">
$.fn.nmkWidget = function() {
	return this.closest( ".nmk-widget" );
};
$.fn.nmkWidgetHeader = function() {
	return this.nmkWidget().children( ".nmk-widget-header" );
};
$.fn.nmkWidgetContent = function() {
	return this.nmkWidget().children( ".nmk-widget-content" );
};
</pre>
<p>This works well for simple plugins like these that don&#8217;t have any dependencies or state management beyond the DOM. But what happens if you have a lot of inter-related functionality that you want to organize into a module? jQuery doesn&#8217;t have support for namespaces in <code>jQuery.fn</code>, but there is a simple pattern that can help. We can define a method that acts as a pass-thru from jQuery to any object:</p>
<pre class="lang:javascript">
var slice = Array.prototype.slice;
$.fn.exec = function( method ) {
	return method.apply( this, slice.call( arguments, 1 ) );
};
</pre>
<p>Then we can create objects, nested as deeply as we want, and define methods on them as if they were standard jQuery methods:</p>
<pre class="lang:javascript">
var nmk = {
	widget: {
		open: function( duration ) {
			return this.nmkWidget().slideDown( duration );
		},
		close: function( duration ) {
			return this.nmkWidget().slideUp( duration );
		}
	}
};
</pre>
<p>We can then execute them using <code>.exec()</code> in any jQuery chain:</p>
<pre class="lang:javascript">
$( elem ).exec( nmk.widget.close );
</pre>
<p>We can even pass parameters to these methods:</p>
<pre class="lang:javascript">
$( elem ).exec( nmk.widget.close, 1000 );
</pre>
<p>Now we&#8217;ve got reusable, modular, namespaced code that can be used directly in jQuery chains. We can use this to define multiple ways to close our widgets without duplicating any logic and without worrying about where we are in the DOM.</p>
<pre class="lang:javascript">
// allow any widget to be closed by a close button located in the header
$( ".nmk-widget-close-button" ).live( "click", function() {
	$( this ).exec( nmk.widget.close );
});

// allow adding a new widget, with undo functionality
$( "#add-widget" ).click(function() {
	// generate a new widget and add to the page
	// returns a jQuery object containing the new widget
	var widget = nmk.widget.create();
	$( "<p>Your new widget has been added. Click here to undo.</p>;" )
		.click(function() {
			widget.exec( nmk.widget.close );
		});
});
</pre>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Long polling in Node.js</title>
		<link>http://blog.nemikor.com/2010/05/21/long-polling-in-nodejs/</link>
		
		<dc:creator><![CDATA[Scott GonzÃ¡lez]]></dc:creator>
		<pubDate>Fri, 21 May 2010 13:19:03 +0000</pubDate>
				<category><![CDATA[Node.js]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[long poll]]></category>
		<category><![CDATA[polling]]></category>
		<guid isPermaLink="false">http://blog.nemikor.com/?p=68</guid>

					<description><![CDATA[Note: Node is currently under heavy development and the API is in a state of flux. This article was written to be compatible with v0.1.95, the most recent version of Node at the time. The examples in this article may not work with future versions. Many web developers seem to think there is some sort&#8230; <a class="more-link" href="http://blog.nemikor.com/2010/05/21/long-polling-in-nodejs/">Continue reading <span class="screen-reader-text">Long polling in Node.js</span></a>]]></description>
										<content:encoded><![CDATA[<p class="note"><strong>Note:</strong> Node is currently under heavy development and the API is in a state of flux. This article was written to be compatible with v0.1.95, the most recent version of Node at the time. The examples in this article may not work with future versions.</p>
<p>Many web developers seem to think there is some sort of black magic behind long polling, either because the language or web server they use doesn&#8217;t support it or because they correlate it with server push technology. In this article, we&#8217;ll show how to implement long polling in <a href="http://nodejs.org">Node.js</a> and explain why you don&#8217;t need to do anything special on the client to support it.</p>
<h3>Request types</h3>
<p>We&#8217;re all familiar with standard web requests: the client requests a resource, the server responds synchronously, then the page is displayed. We&#8217;re also familiar with the concept of ajax requests in which the client requests a resource asynchronously and is notified when the server responds. Typically the server doesn&#8217;t treat ajax requests asynchronously; a request comes in and the server immediately (and synchronously) processes the request and responds. The asynchronous part just happens on the client where the browser doesn&#8217;t block while it waits for the server to respond.</p>
<p>Long polling is an ajax request in which the request and response are both treated as asynchronous operations. Rather than accepting the request and immediately processing to return a result, the server accepts the request and holds on to it until some other event occurs, providing data to send as a response to the original request. Most scripting languages don&#8217;t support holding on to requests for long periods of time because the script runs from top to bottom and then immediately responds. Trying to hold on to requests in these languages would require creating a blocking loop that waits for the relevant event to occur and that would quickly kill your server as requests build up. Node scripts run in an event loop, making them ideal for holding on to requests without blocking other processes.</p>
<h3>Handling requests in Node</h3>
<p>Because Node is specifically built to provide non-blocking I/O, even the Hello World example from the docs shows off an asynchronous response to an HTTP request.</p>
<pre class="lang:javascript">
var http = require("http");
http.createServer(function(request, response) {
	setTimeout(function() {
		response.writeHead(200, { "Content-Type": "text/plain" });
		response.end("Hello, World!");
	}, 2000);
}).listen(8000);
</pre>
<p>When a request comes in, the server will wait two seconds and then respond with &#8220;Hello, World!&#8221;. The important thing in this example is that the script is not blocking while it waits two seconds. This means that other requests can come in during that two second period and be handled immediately. In this case, those additional requests would also wait for two seconds before getting a response, but the response would come two seconds after the request was initiated, not two seconds after the previous request is closed.</p>
<p>Let&#8217;s split the response generation out of the main function to get a better idea of what&#8217;s really going on here.</p>
<pre class="lang:javascript">
var http = require("http");
var requests = [];

http.createServer(function(request, response) {
	// store the response so we can respond later
	requests.push(response);
}).listen(8000);

setInterval(function() {
	// respond to each request
	while (requests.length) {
		response = requests.shift();
		response.writeHead(200, { "Content-Type": "text/plain" });
		response.end("Hello, World!");
	}
}, 2000);
</pre>
<p>There are a few differences between this example and the first example. Right away, we can see that when a request comes in we don&#8217;t make any attempt to respond to it, we just throw the response object into an array and seemingly ignore it. Next we have a function that runs every two seconds and responds to all the requests that we&#8217;re holding on to. Since this interval is based on when the script was started, the request may be held for anywhere between one millisecond and two seconds, depending on how close the request comes in to the next run of the interval. This better represents the standard model for a long polling implementation in which some event not directly related to the request occurs on the server and triggers a response.</p>
<h3>A more complex example</h3>
<p>Let&#8217;s build a script the pipes stdin to HTTP requests. When an HTTP request comes, we&#8217;ll check to see if we have any data already stored from stdin. If we do, we&#8217;ll just respond to the requestÂ immediately; if we don&#8217;t, we&#8217;ll hold on to the request and respond whenever we detect some action from stdin. Likewise, when we receive data from stdin, we&#8217;ll check to see if we have a pending HTTP request. If we do, we&#8217;ll respond to the request with the data that just came in; if we don&#8217;t, we&#8217;ll store the data and respond whenever a request comes in.</p>
<pre class="lang:javascript">
var http = require("http");
var pendingResponse;
var chunks = "";

http.createServer(function(request, response) {
	// if we have data, send it
	if (chunks.length) {
		response.writeHead(200, { "Content-Type": "text/plain" });
		response.end(chunks);
		chunks = "";

	// no data sitting around, store the response for later
	} else {
		pendingResponse = response;
	}
}).listen(8000);

process.openStdin().addListener("data", function(chunk) {
	// if we have a pending request, send the data
	if (pendingResponse) {
		pendingResponse.writeHead(200, { "Content-Type": "text/plain" });
		pendingResponse.end(chunk);
		pendingResponse = null;

	// no pending request, store the chunk from stdin for later
	} else {
		chunks += chunk;
	}
});
</pre>
<h3>Preventing timeouts</h3>
<p>One problem you might run into with long polling is holding on to the request too long. If you take too long to respond, the request will eventually time out. To prevent this from occurring, you can keep track of when the requests come in, and send an empty response if the request is still open after a certain period of time. When the client receives the empty response, it will start the next long poll request. This can easily be accomplished with a slight tweak to the code above that uses an interval to respond to requests. Instead of just responding to all requests, we would check if the request has been pending for too long, and close it out if it has.</p>
<pre class="lang:javascript">
var http = require("http");
var requests = [];

http.createServer(function(request, response) {
	// store the response so we can respond later
	requests.push({
		response: response,
		timestamp: new Date().getTime()
	});
}).listen(8000);

setInterval(function() {
	// close out requests older than 30 seconds
	var expiration = new Date().getTime() - 30000;
	var response;
	for (var i = requests.length - 1; i &gt;= 0; i--) {
		if (requests[i].timestamp &lt; expiration) {
			response = requests[i].response;
			response.writeHead(200, { "Content-Type": "text/plain" });
			response.end("");
		}
	}
}, 1000);
</pre>
<h3>Long polling on the client</h3>
<p>As mentioned above, there&#8217;s nothing special that needs to be done on the client for long polling. The general concept is just to make an ajax request and when you get a response, handle it and make the ajax request again. This process just loops over and over, handling data whenever the server responds.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Building stateful jQuery plugins</title>
		<link>http://blog.nemikor.com/2010/05/15/building-stateful-jquery-plugins/</link>
		
		<dc:creator><![CDATA[Scott GonzÃ¡lez]]></dc:creator>
		<pubDate>Sun, 16 May 2010 01:07:06 +0000</pubDate>
				<category><![CDATA[jQuery UI]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[plugin]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[widget factory]]></category>
		<guid isPermaLink="false">http://blog.nemikor.com/?p=58</guid>

					<description><![CDATA[Background Over the past few years, jQuery has dominated the web development community with its simple, yet brilliant, API. The â€œfind elements, do somethingâ€ pattern and ability to chain function calls together combine to create code that reads like English. jQuery&#8217;s simplicity and almost nonexistent learning curve have made it extremely popular among developers and&#8230; <a class="more-link" href="http://blog.nemikor.com/2010/05/15/building-stateful-jquery-plugins/">Continue reading <span class="screen-reader-text">Building stateful jQuery plugins</span></a>]]></description>
										<content:encoded><![CDATA[<h3>Background</h3>
<p>Over the past few years, jQuery has dominated the web development community with its simple, yet brilliant, API. The â€œfind elements, do somethingâ€ pattern and ability to chain function calls together combine to create code that reads like English. jQuery&#8217;s simplicity and almost nonexistent learning curve have made it extremely popular among developers and designers alike. Equally as important as its ease of use is its extensibility. With an extension system that makes creating a plugin as simple as writing a function, jQuery has been able to maintain a lean core while offering an almost unlimited amount of functionality.</p>
<p>The combination of jQuery&#8217;s simple plugin system and its active community has resulted in over 2,000 plugins being listed in its <a href="http://plugins.jquery.com">plugin repository</a>. However, like all core methods, the majority of these plugins only provide stateless functionality. While many of these plugins are useful, there&#8217;s a large set of functionality that doesn&#8217;t fit into the basic plugin pattern.</p>
<h4>A new plugin system</h4>
<p>In order to fill this gap, jQuery UI has implemented a more advanced plugin system. The new system manages state, allows multiple functions to be exposed via a single plugin, and provides various extension points. This system is called the widget factory and is exposed as <code>jQuery.widget</code>. In this article, we&#8217;ll explore the various features provided by the widget factory by building a simple progress bar plugin using jQuery UI 1.8.</p>
<h3>Building a plugin</h3>
<p>To start, we&#8217;ll create a progress bar that just lets us set the progress once.  As we can see below, this is done by calling <code>jQuery.widget</code> with two parameters: the name of the plugin to create and an object literal containing functions to support our plugin. When our plugin gets called, it will create a new plugin instance and all functions will be executed within the context of that instance. This is different from a standard jQuery plugin in two important ways. First, the context is an object, not a DOM element. Second, the context is always a single object, never a collection.</p>
<pre class="lang:javascript">
$.widget( "nmk.progressbar", {
	_create: function() {
		var progress = this.options.value + "%";
		this.element
			.addClass( "progressbar" )
			.text( progress );
	}
});
</pre>
<p>The name of the plugin must contain a namespace, in this case we&#8217;ve used the nmk namespace. There is currently a limitation that exactly one namespace must be used. We can also see that the widget factory has provided two properties for us. <code>this.element</code> is a jQuery object containing exactly one element. If our plugin is called on a jQuery object containing multiple elements, a separate plugin instance will be created for each element, and each instance will have its own <code>this.element</code>. The second property, <code>this.options</code>, is a hash containing key/value pairs for all of our plugin&#8217;s options. These options can be passed to our plugin as shown here.</p>
<pre class="lang:javascript">
$( "<div></div>" )
	.appendTo( "body" )
	.progressbar({ value: 20 });
</pre>
<p>When we call <code>jQuery.widget</code> it extends jQuery by adding a function to <code>jQuery.fn</code> (the system for creating a standard plugin). The name of the function it adds is based on the name you pass to <code>jQuery.widget</code>, without the namespace; in our case â€œprogressbarâ€. The options passed to our plugin are the values that get set in <code>this.options</code> inside of our plugin instance. As shown below, we can specify default values for any of our options. When designing your API, you should figure out the most common use case for your plugin so that you can set appropriate default values and make all options truly optional.</p>
<pre class="lang:javscript">
$.widget( "nmk.progressbar", {
	// default options
	options: {
		value: 0
	},
	_create: function() {
		var progress = this.options.value + "%";
		this.element
			.addClass( "progressbar" )
			.text( progress );
	}
});
</pre>
<h4>Calling plugin methods</h4>
<p>Now that we can initialize our progress bar, we&#8217;ll add the ability to perform actions by calling methods  on our plugin instance. To define a plugin method, we just include the function in the object literal that we pass to <code>jQuery.widget</code>. We can also define â€œprivateâ€ methods by prepending an underscore to the function name.</p>
<pre class="lang:javscript">
$.widget( "nmk.progressbar", {
	options: {
		value: 0
	},
	_create: function() {
		var progress = this.options.value + "%";
		this.element
			.addClass( "progressbar" )
			.text( progress );
	},
	// create a public method
	value: function( value ) {
		// no value passed, act as a getter
		if ( value === undefined ) {
			return this.options.value;
		// value passed, act as a setter
		} else {
			this.options.value = this._constrain( value );
			var progress = this.options.value + "%";
			this.element.text( progress );
		}
	},
	// create a private method
	_constrain: function( value ) {
		if ( value > 100 ) {
			value = 100;
		}
		if ( value < 0 ) {
			value = 0;
		}
		return value;
	}
});
</pre>
<p>To call a method on a plugin instance, you pass the name of the method to the jQuery plugin. If you are calling a method that accepts parameters, you simply pass those parameters after the method name.</p>
<p class="note"><strong>Note:</strong> Executing methods by passing the method name to the same jQuery function that was used to initialize the plugin may seem odd. This is done to prevent pollution of the jQuery namespace while maintaining the ability to chain method calls. Later in this article we'll see alternative uses that may feel more natural.</p>
<pre class="lang:javascript">
var bar = $( "<div></div>" )
	.appendTo( "body" )
	.progressbar({ value: 20 });

// get the current value
alert( bar.progressbar( "value" ) );

// update the value
bar.progressbar( "value", 50 );

// get the current value again
alert( bar.progressbar( "value" ) );
</pre>
<h4>Working with options</h4>
<p>One of the methods that is automatically available to our plugin is the <code>option</code> method. The <code>option</code> method allows you to get and set options after initialization. This method works exactly like jQuery's <code>css</code> and <code>attr</code> methods: you can pass just a name to use it as a setter, a name and value to use it as a single setter, or a hash of name/value pairs to set multiple values. When used as a getter, the plugin will return the current value of the option that corresponds to the name that was passed in. When used as a setter, the plugin's <code>_setOption</code> method will be called for each option that is being set. We can specify a <code>_setOption</code> method in our plugin to react to option changes.</p>
<pre class="lang:javascript">
$.widget( "nmk.progressbar", {
	options: {
		value: 0
	},
	_create: function() {
		this.element.addClass( "progressbar" );
		this._update();
	},
	_setOption: function( key, value ) {
		this.options[ key ] = value;
		this._update();
	},
	_update: function() {
		var progress = this.options.value + "%";
		this.element.text( progress );
	}
});
</pre>
<h4>Adding callbacks</h4>
<p>One of the easiest ways to make your plugin extensible is to add callbacks so users can react when the state of your plugin changes. We can see below how to add a callback to our progress bar to signify when the progress has reached 100%. The <code>_trigger</code> method takes three parameters: the name of the callback, a native event object that initiated the callback, and a hash of data relevant to the event. The callback name is the only required parameter, but the others can be very useful for users who want to implement custom functionality on top of your plugin. For example, if we were building a draggable plugin, we could pass the native mousemove event when triggering a drag callback; this would allow users to react to the drag based on the x/y coordinates provided by the event object.</p>
<pre class="lang:javascript">
$.widget( "nmk.progressbar", {
	options: {
		value: 0
	},
	_create: function() {
		this.element.addClass( "progressbar" );
		this._update();
	},
	_setOption: function( key, value ) {
		this.options[ key ] = value;
		this._update();
	},
	_update: function() {
		var progress = this.options.value + "%";
		this.element.text( progress );
		if ( this.options.value == 100 ) {
			this._trigger( "complete", null, { value: 100 } );
		}
	}
});
</pre>
<p>Callback functions are essentially just additional options, so you can get and set them just like any other option. Whenever a callback is executed, a corresponding event is triggered as well. The event type is determined by concatenating the plugin name and the callback name. The callback and event both receive the same two parameters: an event object and a hash of data relevant to the event, as we'll see below. Your plugin may have functionality that you want to allow the user to prevent. The best way to support this is by creating cancelable callbacks. User's can cancel a callback, or its associated event, the same way they cancel any native event, by calling event.preventDefault() or returning false. If the user cancels the callback, the <code>_trigger</code> method will return false so you can implement the appropriate functionality within your plugin.</p>
<pre class="lang:javascript">
var bar = $( "<div></div>" )
	.appendTo( "body" )
	.progressbar({
		complete: function( event, data ) {
			alert( "Callbacks are great!" );
		}
	})
	.bind( "progressbarcomplete", function( event, data ) {
		alert( "Events bubble and support many handlers for extreme flexibility." );
		alert( "The progress bar value is " + data.value );
	});

bar.progressbar( "option", "value", 100 );
</pre>
<h3>Looking under the hood</h3>
<p>Now that we've seen how to build a plugin using the widget factory, let's take a look at how it actually works. When you call <code>jQuery.widget</code>, it creates a constructor for your plugin and sets the object literal that you pass in as the prototype for your plugin instances. All of the functionality that automatically gets added to your plugin comes from a base widget prototype, which is defined as <code>jQuery.Widget.prototype</code>. When a plugin instance is created, it is stored on the original DOM element using <code>jQuery.data</code>, with the plugin name as the key.<br />
Because the plugin instance is directly linked to the DOM element, you can access the plugin instance directly instead of going through the exposed plugin method if you want. This will allow you to call methods directly on the plugin instance instead of passing method names as strings and will also give you direct access to the plugin's properties.</p>
<pre class="lang:javascript">
var bar = $( "<div></div>" )
	.appendTo( "body" )
	.progressbar()
	.data( "progressbar" );

// call a method directly on the plugin instance
bar.option( "value", 50 );

// access properties on the plugin instance
alert( bar.options.value );
</pre>
<h4>Extending a plugin's prototype</h4>
<p>One of the biggest benefits of having a constructor and prototype for a plugin is the ease of extending the plugin. By adding or modifying methods on the plugin's prototype, we can modify the behavior of all instances of our plugin. For example, if we wanted to add a method to our progress bar to reset the progress to 0% we could add this method to the prototype and it would instantly be available to be called on any plugin instance.</p>
<pre class="lang:javascript">
$.nmk.progressbar.prototype.reset = function() {
	this._setOption( "value", 0 );
};
</pre>
<h4>Cleaning up</h4>
<p>In some cases, it will make sense to allow users to apply and then later unapply your plugin. You can accomplish this via the <code>destroy</code> method. Within the <code>destroy</code> method, you should undo anything your plugin may have done during initialization or later use. The destroy method is automatically called if the element that your plugin instance is tied to is removed from the DOM, so this can be used for garbage collection as well. The default <code>destroy</code> method removes the link between the DOM element and the plugin instance, so it's important to call the base function from your plugin's destroy method.</p>
<pre class="lang:javascript">
$.widget( "nmk.progressbar", {
	options: {
		value: 0
	},
	_create: function() {
		this.element.addClass( "progressbar" );
		this._update();
	},
	_setOption: function( key, value ) {
		this.options[ key ] = value;
		this._update();
	},
	_update: function() {
		var progress = this.options.value + "%";
		this.element.text( progress );
		if ( this.options.value == 100 ) {
			this._trigger( "complete", null, { value: 100 } );
		}
	},
	destroy: function() {
		this.element
			.removeClass( "progressbar" )
			.text("");

		// call the base destroy function
		$.Widget.prototype.destroy.call( this );
	}
});
</pre>
<h3>Closing comments</h3>
<p>The widget factory is only one way of creating stateful plugins. There are a few different models that can be used and each have their own advantages and disadvantages. The widget factory solves lots of common problems for you and can greatly improve productivity, it also greatly improves code reuse, making it a great fit for jQuery UI as well as many other stateful plugins.</p>
<p>You may have noticed that in this article we used the nmk namespace. The ui namespace is reserved for official jQuery UI plugins. When building your own plugins, you should create your own namespace. This makes it clear where the plugin came from and if it is part of a larger collection.</p>
<p><a href="http://example.nemikor.com/building-stateful-jquery-plugins">View this example in a new window</a></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Using multiple versions of jQuery</title>
		<link>http://blog.nemikor.com/2009/10/03/using-multiple-versions-of-jquery/</link>
		
		<dc:creator><![CDATA[Scott GonzÃ¡lez]]></dc:creator>
		<pubDate>Sat, 03 Oct 2009 04:52:48 +0000</pubDate>
				<category><![CDATA[jQuery]]></category>
		<category><![CDATA[multiple]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[versions]]></category>
		<guid isPermaLink="false">http://blog.nemikor.com/?p=39</guid>

					<description><![CDATA[Whenever a new version of jQuery comes out, there are several reasons to upgrade; new features, bug fixes and performance are generally the most common. However, it&#8217;s not always possible to upgrade as soon as a new version comes out. The new version may contain an API change that would break some of your functionality&#8230; <a class="more-link" href="http://blog.nemikor.com/2009/10/03/using-multiple-versions-of-jquery/">Continue reading <span class="screen-reader-text">Using multiple versions of jQuery</span></a>]]></description>
										<content:encoded><![CDATA[<p>Whenever a new version of jQuery comes out, there are several reasons to upgrade; new features, bug fixes and performance are generally the most common. However, it&#8217;s not always possible to upgrade as soon as a new version comes out. The new version may contain an API change that would break some of your functionality or you may be using a plugin that isn&#8217;t compatible with the new version. This is where <code>jQuery.noConflict()</code> comes in.</p>
<h3>History of jQuery.noConflict()</h3>
<p><code>jQuery.noConflict()</code> was added in v1.1 to support loading jQuery on a page with other code that uses the global <code>$</code> variable. In this version, the only thing that <code>jQuery.noConflict()</code> did was revert the <code>$</code> variable to what it was before jQuery was loaded. In v1.1.1, this function was modified to also return the jQuery object so that you could assign jQuery to another variable (though it was still also assigned to the global <code>jQuery</code> variable). v1.1.4 introduced a boolean parameter for <code>jQuery.noConflict()</code> to indicate whether the global <code>jQuery</code> variable should be reverted; this option was added to make it easy to load multiple versions of jQuery on the same page.</p>
<h3>Using jQuery.noConflict()</h3>
<p>Using <code>jQuery.noConflict()</code> to load multiple versions of jQuery is actually pretty simple. There&#8217;s essentially just one rule: load your plugins in the correct order. In order for this to work, you have to include one version of jQuery and all of the plugins for that version before including the next version and all of its plugins. You can call <code>jQuery.noConflict()</code> immediately before including the second version or after you have included all the plugins for the second version. Both methods will have the same final outcome, but it may be easier to keep track of what&#8217;s going on if you call <code>jQuery.noConflict()</code> immediately before loading the next version in the unlikely event that you need to include more than two versions of jQuery on the same page. Because this method is slightly easier to follow, we&#8217;ll use it in our example.</p>
<p>First we need to load both versions of jQuery:</p>
<pre class="lang:html">
<!-- load jQuery 1.1.3 -->
<script type="text/javascript" src="http://code.jquery.com/jquery-1.1.3.js"></script>
<script type="text/javascript" src="jquery.dimensions.min.js"></script>

<!-- revert global jQuery and $ variables and store jQuery in a new variable -->
<script type="text/javascript">
var jQuery_1_1_3 = $.noConflict(true);
</script>

<!-- load jQuery 1.3.2 -->
<script type="text/javascript" src="http://code.jquery.com/jquery-1.3.2.js"></script>

<!-- revert global jQuery and $ variables and store jQuery in a new variable -->
<script type="text/javascript">
var jQuery_1_3_2 = $.noConflict(true);
</script>
</pre>
<p>Now we can use either version of jQuery by using the two new variables we&#8217;ve created:</p>
<pre class="lang:javascript">
jQuery_1_1_3('<button>Use jQuery 1.1.3</button>')
	.click(function() {
		alert('Top: ' + jQuery_1_1_3(this).offset().top + '\n' +
			'jQuery: ' + jQuery_1_1_3.fn.jquery);
	})
	.appendTo('body');
</pre>
<p>This is great, but you&#8217;re probably looking at that code and thinking &#8220;I wish I could still use the <code>$</code> variable.&#8221; Well, with a little help from a self-executing anonymous function, you can!</p>
<pre class="lang:javascript">
(function($) {
	$('<button>Use jQuery 1.1.3</button>')
		.click(function() {
			alert('Top: ' + $(this).offset().top + '\n' +
				'jQuery: ' + $.fn.jquery);
		})
		.appendTo('body');
})(jQuery_1_1_3);
</pre>
<p>This is a pattern you&#8217;ll see in a lot of plugins (in fact it&#8217;s part of what makes this whole thing work). We&#8217;ve created a function that accepts a single parameter, <code>$</code>, and we call that function as soon as we define it, passing our jQuery object to it. Now we can reference our jQuery object as <code>$</code> inside this function. This makes it very easy to rename your global jQuery object while keeping your existing code working with minimal modifications.</p>
<p><a href="http://example.nemikor.com/using-multiple-versions-of-jquery/">View this example in a new window</a></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Creating dialogs on demand</title>
		<link>http://blog.nemikor.com/2009/08/07/creating-dialogs-on-demand/</link>
		
		<dc:creator><![CDATA[Scott GonzÃ¡lez]]></dc:creator>
		<pubDate>Fri, 07 Aug 2009 20:40:30 +0000</pubDate>
				<category><![CDATA[jQuery UI - Dialog]]></category>
		<category><![CDATA[cache]]></category>
		<category><![CDATA[dialog link]]></category>
		<category><![CDATA[first]]></category>
		<category><![CDATA[hijax]]></category>
		<category><![CDATA[second]]></category>
		<category><![CDATA[tutorial]]></category>
		<guid isPermaLink="false">http://blog.nemikor.com/?p=22</guid>

					<description><![CDATA[In a previous article, I explained how to load a page into a dialog. The article focused on a simple solution to keep it easy to understand. However, that simplicity does come with a drawback; the page contents are loaded immediately after the document is ready, even if the user never opens the dialog. In&#8230; <a class="more-link" href="http://blog.nemikor.com/2009/08/07/creating-dialogs-on-demand/">Continue reading <span class="screen-reader-text">Creating dialogs on demand</span></a>]]></description>
										<content:encoded><![CDATA[<p>In a previous article, I explained <a href="/2009/04/18/loading-a-page-into-a-dialog/">how to load a page into a dialog</a>. The article focused on a simple solution to keep it easy to understand. However, that simplicity does come with a drawback; the page contents are loaded immediately after the document is ready, even if the user never opens the dialog. In this article, I&#8217;ll show how to load the page on demand while still only making a single request regardless of how many times the user opens the dialog.</p>
<h3>On-demand page loading</h3>
<p>In order to create the dialog on the first click, we&#8217;ll take advantage of <a href="http://docs.jquery.com/Events/one">jQuery&#8217;s <code>.one()</code> event binding method</a>.Â <code>.one()</code> binds a handler to an event, but the handler is only ever run once. Immediately after the handler runs it unbinds itself, preventing further execution. We&#8217;ll adapt the example from the previous article to take advantage of <code>.one()</code>:</p>
<pre class="lang:javascript">
$(document).ready(function() {
	$('#page-help').each(function() {
		var $dialog = $('<div></div>');
		var $link = $(this).one('click', function() {
			$dialog
				.load($link.attr('href'))
				.dialog({
					title: $link.attr('title'),
					width: 500,
					height: 300
				});

			$link.click(function() {
				$dialog.dialog('open');

				return false;
			});

			return false;
		});
	});
});
</pre>
<h3>Adding the final touch</h3>
<p>Now that we&#8217;ve got our dialogs loading on demand, we need to account for network latency, slow connections, etc. Previously we were loading the page contents before the user ever saw the dialog, so any delay was hidden. A simple solution for this is to just show a loading image inside the dialog until the page contents are loaded. We&#8217;ll load this image immediately on document ready to make sure that it&#8217;s ready for use when the user clicks the link to open the dialog. Loading images are generally very small in terms of file size and they can be cached by the user, so the overhead of loading the image up-front is negligible.</p>
<pre class="lang:javascript">
$(document).ready(function() {
	var $loading = $('<img decoding="async" src="loading.gif" alt="loading">');

	$('#page-help').each(function() {
		var $dialog = $('<div></div>')
			.append($loading.clone());
		var $link = $(this).one('click', function() {
			$dialog
				.load($link.attr('href'))
				.dialog({
					title: $link.attr('title'),
					width: 500,
					height: 300
				});

			$link.click(function() {
				$dialog.dialog('open');

				return false;
			});

			return false;
		});
	});
});
</pre>
<p><a href="http://example.nemikor.com/creating-dialogs-on-demand">View this example in a new window</a></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Loading a page into a dialog</title>
		<link>http://blog.nemikor.com/2009/04/18/loading-a-page-into-a-dialog/</link>
		
		<dc:creator><![CDATA[Scott GonzÃ¡lez]]></dc:creator>
		<pubDate>Sun, 19 Apr 2009 01:54:28 +0000</pubDate>
				<category><![CDATA[jQuery UI - Dialog]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[dialog link]]></category>
		<category><![CDATA[hijax]]></category>
		<category><![CDATA[tutorial]]></category>
		<guid isPermaLink="false">http://blog.nemikor.com/?p=21</guid>

					<description><![CDATA[I previously showed the basic usage of the jQuery UI dialog.Â  In this article, I&#8217;ll show how to open a page in a dialog.Â  We&#8217;ve all been to sites where there&#8217;s a help link that opens a popup with some short help text.Â  This is usually done with a simple window.open call attached to the&#8230; <a class="more-link" href="http://blog.nemikor.com/2009/04/18/loading-a-page-into-a-dialog/">Continue reading <span class="screen-reader-text">Loading a page into a dialog</span></a>]]></description>
										<content:encoded><![CDATA[<p>I previously showed the <a href="http://blog.nemikor.com/2009/04/08/basic-usage-of-the-jquery-ui-dialog/">basic usage of the jQuery UI dialog</a>.Â  In this article, I&#8217;ll show how to open a page in a dialog.Â  We&#8217;ve all been to sites where there&#8217;s a help link that opens a popup with some short help text.Â  This is usually done with a simple <code>window.open</code> call attached to the click event of the link.</p>
<pre class="lang:html">
<a id="page-help" href="page.html" onclick="window.open(this.href, 'popupwindow', 'width=500,height=300'); return false;">what is this?</a>
</pre>
<h3>Making it better</h3>
<p>The one thing that this code has going for it is that users without JavaScript will still be able to get to the page with the help content.  Of course, a better implementation would move the JavaScript out of the HTML, properly separating content from behavior.Â  We can spruce this up by loading the content into a dialog instead of a new window:</p>
<pre class="lang:javascript">
$(document).ready(function() {
	$('#page-help').each(function() {
		var $link = $(this);
		var $dialog = $('<div></div>')
			.load($link.attr('href'))
			.dialog({
				autoOpen: false,
				title: $link.attr('title'),
				width: 500,
				height: 300
			});

		$link.click(function() {
			$dialog.dialog('open');

			return false;
		});
	});
});
</pre>
<h3>How it works</h3>
<p>We&#8217;re finding the link, loading the contents of the linked page into a div and creating a dialog from that div.Â  We then bind a click event to the link to show the dialog.Â  This code by itself will work in many situations.Â  However, the page you&#8217;re linking to may have a heading that you&#8217;re already reproducing with the dialog title.Â  There may also be other elements on the page that won&#8217;t make sense in a popup, such as navigational elements or a page footer.Â  Luckily the <code>.load()</code> function allows us to pass in a selector to find the contents that we care about.Â  In this example we&#8217;ll assume the main content of the page is in a div with an id of content.</p>
<pre class="lang:javascript">
$(document).ready(function() {
	$('#page-help').each(function() {
		var $link = $(this);
		var $dialog = $('<div></div>')
			.load($link.attr('href') + ' #content')
			.dialog({
				autoOpen: false,
				title: $link.attr('title'),
				width: 500,
				height: 300
			});

		$link.click(function() {
			$dialog.dialog('open');

			return false;
		});
	});
});
</pre>
<p><a href="http://example.nemikor.com/loading-a-page-into-a-dialog/">View this example in a new window</a></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Basic usage of the jQuery UI dialog</title>
		<link>http://blog.nemikor.com/2009/04/08/basic-usage-of-the-jquery-ui-dialog/</link>
		
		<dc:creator><![CDATA[Scott GonzÃ¡lez]]></dc:creator>
		<pubDate>Thu, 09 Apr 2009 02:05:40 +0000</pubDate>
				<category><![CDATA[jQuery UI - Dialog]]></category>
		<category><![CDATA[dialog]]></category>
		<category><![CDATA[first]]></category>
		<category><![CDATA[once]]></category>
		<category><![CDATA[open]]></category>
		<category><![CDATA[second]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[twice]]></category>
		<guid isPermaLink="false">http://blog.nemikor.com/?p=3</guid>

					<description><![CDATA[The jQuery UI dialog, like many jQuery UI plugins, is extremely easy to get started with but has a few areas that causes new users some trouble.Â  One of the most commonly asked questions on the jquery-ui list is &#8220;Why does my dialog only open once?&#8221;Â  In this article I&#8217;ll explain the problem these users&#8230; <a class="more-link" href="http://blog.nemikor.com/2009/04/08/basic-usage-of-the-jquery-ui-dialog/">Continue reading <span class="screen-reader-text">Basic usage of the jQuery UI dialog</span></a>]]></description>
										<content:encoded><![CDATA[<p>The <a href="http://jqueryui.com/docs/dialog/">jQuery UI dialog</a>, like many jQuery UI plugins, is extremely easy to get started with but has a few areas that causes new users some trouble.Â  One of the most commonly asked questions on the <a href="http://groups.google.com/group/jquery-ui">jquery-ui list</a> is &#8220;Why does my dialog only open once?&#8221;Â  In this article I&#8217;ll explain the problem these users are running into and how to get your dialogs to show each and every time.</p>
<h3>Problem:</h3>
<p>All jQuery UI plugins maintain state, such as the current option values, whether the plugin is enabled or disabled, which plugins have been initialized on the element, etc.Â  This state persists from the time the plugin is instantiated on the element until it is destroyed, either explicitly by the user calling <code>.pluginName('destroy')</code> or by removing the element (or one of its ancestors) via <code>.remove()</code>.Â  Because of this state management, you cannot instantiate the same plugin on an element multiple times, unless you destroy the plugin instance first.</p>
<p>The problem that users often encounter with dialogs is that they try to instantiate a new dialog every time the user performs some action (generally clicking a link or a button).Â  This is an understandable mistake because at first glance it seems like calling <code>.dialog()</code> on an element is what causes the dialog to open.Â  In reality what is happening is that a new dialog instance is being created and then that instance is being opened immediately after instantiation.Â  The reason that the dialog opens is because dialogs have an <code>autoOpen</code> option, which defaults to <code>true</code>.Â  So when a user calls <code>.dialog()</code> on an element twice, the second call is ignored because the dialog has already been instantiated on that element.</p>
<h3>Solution:</h3>
<p>The simple solution to this problem is to instantiate the dialog with <code>autoOpen</code> set to <code>false</code> and then call <code>.dialog('open')</code> in the event handler.</p>
<pre class="lang:javascript">
$(document).ready(function() {
	var $dialog = $('<div></div>')
		.html('This dialog will show every time!')
		.dialog({
			autoOpen: false,
			title: 'Basic Dialog'
		});

	$('#opener').click(function() {
		$dialog.dialog('open');
		// prevent the default action, e.g., following a link
		return false;
	});
});
</pre>
<p><a href="http://example.nemikor.com/basic-usage-of-the-jquery-ui-dialog/">View this example in a new window</a></p>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>
