<?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>Ashita.org</title>
	<atom:link href="http://www.ashita.org/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.ashita.org</link>
	<description></description>
	<lastBuildDate>Thu, 22 Apr 2010 17:21:34 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Getting the source window of a request</title>
		<link>http://www.ashita.org/getting-the-source-window-of-a-request/</link>
		<comments>http://www.ashita.org/getting-the-source-window-of-a-request/#comments</comments>
		<pubDate>Mon, 12 Oct 2009 06:35:02 +0000</pubDate>
		<dc:creator>Jonathan Fingland</dc:creator>
				<category><![CDATA[Firefox]]></category>
		<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://ashita.org/?p=320</guid>
		<description><![CDATA[This post draws heavily on a question and answer on &#8220;An observer for URL changes (Firefox extension)&#8221; from StackOverflow.
In this post, however, I&#8217;m going to focus only on getting the window from which an http request originated.


What you need to know
Yesterday&#8217;s post about XHR Listening by a Firefox Addon gives a good basis to work [...]]]></description>
			<content:encoded><![CDATA[<p>This post draws heavily on a question and answer on &#8220;<a href="http://stackoverflow.com/questions/1549831/an-observer-for-url-changes-firefox-extension">An observer for URL changes (Firefox extension)</a>&#8221; from <a href="http://www.stackoverflow.com">StackOverflow</a>.</p>
<p>In this post, however, I&#8217;m going to focus only on getting the window from which an http request originated.</p>
<ul class='structure'>
<li>
<h3>What you need to know</h3>
<p>Yesterday&#8217;s post about <a href="http://ashita.org/howto-xhr-listening-by-a-firefox-addon/">XHR Listening by a Firefox Addon</a> gives a good basis to work from so I will assume you&#8217;ve read over that and understood it (you if haven&#8217;t read it, do so now).
</li>
<li>
<h3>Organization and code</h3>
<p>In the case on StackOverflow, the logic was all in the observer, not the TracingListener. It also makes a good example of how to get selected data.</p>
<pre><code class='javascript'>

var myObserver = {
   observe: function(aSubject, aTopic, aData){
          if (aTopic == 'http-on-examine-response')
          {
                var oHttp = aSubject.QueryInterface(Ci.nsIHttpChannel);
                var interfaceRequestor =   oHttp.notificationCallbacks
                                               .QueryInterface(Ci.nsIInterfaceRequestor);
                aSubject.DOMWindow = interfaceRequestor.getInterface(Ci.nsIDOMWindow);
          }
     }
   },

   QueryInterface: function(iid){
      if (!iid.equals(Ci.nsISupports) &#038;&#038;
          !iid.equals(Ci.nsIObserver))
        throw Components.results.NS_ERROR_NO_INTERFACE;

      return this;
   }
}
</code></pre>
<ul class='structure'>
<li>
<h4>How does it work?</h4>
<p>The three lines after our topic check very simply <code>QueryInterface</code> into <code>nsIHttpChannel</code> (like we had to with getting the <code>URI </code>and <code>requestMethod</code>), then the tricky bit is the next two steps: getting the channel&#8217;s <a href="http://">notificationCallbacks</a> and <code>QueryInterface</code>-ing into an <a href="http://www.oxymoronical.com/experiments/xpcomref/applications/Firefox/3.5/interfaces/nsIInterfaceRequestor">nsIInterfaceRequestor</a>, and then calling <code>getInterface </code>to get an <code>nsIDOMWindow</code>. <code>nsIInterfaceRequestor</code> provides a single method, <code>getInterface</code>, which is very similar to <code>QueryInterface</code>, but not the same (See the nsIInterfaceRequestor docs for more info).
</li>
</ul>
</li>
<li>
<h3>Finishing up</h3>
<p> All that&#8217;s left is to register the observer</p>
<pre><code class='javascript'>
var observerService = Cc["@mozilla.org/observer-service;1"]
    .getService(Ci.nsIObserverService);

observerService.addObserver(myObserver,
    "http-on-examine-response", false);
</code></pre>
</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.ashita.org/getting-the-source-window-of-a-request/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Howto: XHR Listening by a Firefox Addon</title>
		<link>http://www.ashita.org/howto-xhr-listening-by-a-firefox-addon/</link>
		<comments>http://www.ashita.org/howto-xhr-listening-by-a-firefox-addon/#comments</comments>
		<pubDate>Sun, 11 Oct 2009 04:00:38 +0000</pubDate>
		<dc:creator>Jonathan Fingland</dc:creator>
				<category><![CDATA[Firefox]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Pirate Questing]]></category>
		<category><![CDATA[AJAX]]></category>
		<category><![CDATA[Firefox Extension]]></category>
		<category><![CDATA[XmlHttpRequest]]></category>

		<guid isPermaLink="false">http://ashita.org/?p=307</guid>
		<description><![CDATA[The following post draws significantly from a post by Jan Odvarko at http://www.softwareishard.com/blog/firebug/nsitraceablechannel-intercept-http-traffic/ but goes a bit further. There are also some sections which were inspired by Firebug, but are heavily modified.


What you need to know
Before I get into the code, understand that one of the most important things in this process to understand is [...]]]></description>
			<content:encoded><![CDATA[<p>The following post draws significantly from a post by Jan Odvarko at <a href="http://www.softwareishard.com/blog/firebug/nsitraceablechannel-intercept-http-traffic/">http://www.softwareishard.com/blog/firebug/nsitraceablechannel-intercept-http-traffic/</a> but goes a bit further. There are also some sections which were inspired by <a href="http://www.getfirebug.com">Firebug</a>, but are heavily modified.</p>
<ul class='structure'>
<li>
<h3>What you need to know</h3>
<p>Before I get into the code, understand that one of the most important things in this process to understand is that your extension&#8217;s listener is just one in a chain. It is the responsibility of every listener in the chain to pass on the information. Failure to do this has some amusing consequences&#8230;. like nothing loading in the browser.</p>
<p>Just to make it really clear &#8212; <em>Don&#8217;t drop the ball</em>. (Edit: And while you <em>can</em> edit the data in the stream &#8212; don&#8217;t do it unless you have a really good reason.)
</li>
<li>
<h3>Convenience methods and aliases</h3>
<p>A lot of the Firefox internals are accessed using <code>Components.classes</code> and <code>Components.interfaces</code>. While the verbosity makes it clear, it can at times be overly repetitive and, honestly, can take a long time to write out. A fairly common shorthand is in use, <code>Cc</code> and <code>Ci</code> with a few other less common shorthands like <code>CCIN</code> (for creating instances of a class based on a class name and an interface name) and <code>CCSV</code> (similarly creating a service based on a class name and interface name)</p>
<pre><code class='javascript'>
if (typeof Cc == "undefined") {
	var Cc = Components.classes;
}
if (typeof Ci == "undefined") {
        var Ci = Components.interfaces;
}
if (typeof CCIN == "undefined") {
	function CCIN(cName, ifaceName){
		return Cc[cName].createInstance(Ci[ifaceName]);
	}
}
if (typeof CCSV == "undefined") {
	function CCSV(cName, ifaceName){
		if (Cc[cName])
			// if fbs fails to load, the error can be _CC[cName] has no properties
			return Cc[cName].getService(Ci[ifaceName]);
		else
			dumpError("CCSV fails for cName:" + cName);
	};
}</code></pre>
<ul class='structure'>
<li>
<h4>What&#8217;s with all of the <code>typeof</code> checks?</h4>
<p>Firebug, gotta love it, but it declares the same things using <code>const</code>. Inside of an <code>if()</code> block, a <code>const</code> is still seen and conflicts, even when the if condition evaluates to <code>false</code>. The code above is essentially a workaround to satisfy both possibilities. <em>If the user has firebug installed, then carry on; if the user doesn&#8217;t have firebug installed, declare those shorthands</em>
</li>
</ul>
</li>
<li>
<h3>The constructor</h3>
<pre><code class='javascript'>function TracingListener() {
}</code></pre>
<p>Above is a (very) simple constructor function for us to create objects from. The methods and properties on the prototype are below. Note that while I could have changed the structure to accommodate better data-hiding, the method below reduces the number of new functions created by making them all declared only once on the prototype. Functions in the constructor are recreated every time the constructor is called with <code>new yourConstructor()</code> whereas functions on the prototype are shared by all instances.
</li>
<li>
<h3>The prototype definition</h3>
<ul class='structure'>
<li>
<h4>Basic properties</h4>
<pre><code class='javascript'>TracingListener.prototype =
{
    originalListener: null,
    receivedData: null,   //will be an array for incoming data.
</code></pre>
<p>The first part of the prototype definition is setting up some basic properties. Note that both are assigned <code>null</code>. These properties will exist on all instances of <code>TracingListener</code>, and thus not be <code>undefined</code> if/when checking. In the case of <code>receivedData</code>, do not be tempted to make it an array here. Remember that methods and properties on the prototype are shared by <em>all</em> instances of the same type &#8212; and we don&#8217;t want all instances to share the same array for data.</p>
<p>Also worth note is that <code>receivedData</code> is a good candidate for data-hiding and declaring it local to the constructor&#8230; but scope and visibility limitations would mean the functions requiring access to it would either need to be in the constructor as well, or have accessor and mutator methods for it. If you&#8217;re making a Singleton or a small number of instances, declaring functions in the constructor is no big deal, but this listener will be instantiated hundreds or thousands of times and it&#8217;s important to keep the duplication to a minimum.
</li>
<li>
<h4>Methods on the prototype</h4>
<ul class='structure'>
<li>
<h5>Interface Requirements</h5>
<pre><code class='javascript'>    //For the listener this is step 1.
    onStartRequest: function(request, context) {
    	this.receivedData = []; //initialize the array

	//Pass on the onStartRequest call to the next listener in the chain -- VERY IMPORTANT
	this.originalListener.onStartRequest(request, context);
    },</code></pre>
<p><code>onStartRequest</code> is the first thing called when the actual request processing begins. This is also the best opportunity to initialize the array on <em>this</em> listener.</p>
<pre><code class='javascript'>    //This is step 2. This gets called every time additional data is available
    onDataAvailable: function(request, context, inputStream, offset, count)
    {
       var binaryInputStream = CCIN("@mozilla.org/binaryinputstream;1",
                                 "nsIBinaryInputStream");
        binaryInputStream.setInputStream(inputStream);

        var storageStream = CCIN("@mozilla.org/storagestream;1",
                                 "nsIStorageStream");
        //8192 is the segment size in bytes, count is the maximum size of the stream in bytes
        storageStream.init(8192, count, null); 

	var binaryOutputStream = CCIN("@mozilla.org/binaryoutputstream;1",
                                 "nsIBinaryOutputStream");
        binaryOutputStream.setOutputStream(storageStream.getOutputStream(0));

        // Copy received data as they come.
        var data = binaryInputStream.readBytes(count);

        this.receivedData.push(data);

        binaryOutputStream.writeBytes(data, count);

        //Pass it on down the chain
        this.originalListener.onDataAvailable(request,
                                          context,
                                          storageStream.newInputStream(0),
                                          offset,
                                          count);
    },</code></pre>
<p><code>onDataAvailable</code> essentially copies the data from the <a href="http://www.oxymoronical.com/experiments/apidocs/interface/nsIBinaryInputStream"><code>binaryInputStream</code></a> to our <code>receivedData</code> array and to the <a href="http://www.oxymoronical.com/experiments/apidocs/interface/nsIStorageStream"><code>storageStream</code></a> (via the <a href="http://www.oxymoronical.com/experiments/apidocs/interface/nsIBinaryOutputStream"><code>binaryOutputStream</code></a>). Then we pass a new <code>InputStream</code> from our <code>storageStream</code> onto the next listener in the chain.</p>
<pre><code class='javascript'>    onStopRequest: function(request, context, statusCode)
    {
	try
	{
                //QueryInterface into HttpChannel to access originalURI and requestMethod properties
		request.QueryInterface(Ci.nsIHttpChannel);

                //this is specific to the PirateQuesting Add-on, but is left here as an example of how to modify behaviour based on the requested URL
		if (request.originalURI
                    &amp;&amp; piratequesting.baseURL == request.originalURI.prePath
                    &amp;&amp; request.originalURI.path.indexOf("/index.php?ajax=") == 0)
		{

			var data = null;
			if (request.requestMethod.toLowerCase() == "post")
			{
				var postText = this.readPostTextFromRequest(request, context);
				if (postText)
					data = ((String)(postText)).parseQuery();

			}

                        //Combine the response into a single string
			var responseSource = this.receivedData.join('');

			//fix leading spaces bug
			//(FM occasionally adds spaces to the beginning of their ajax responses...
                        //which breaks the XML)
			responseSource = responseSource.replace(/^\s+(\S[\s\S]+)/, "$1");

                        //gets the date from the response headers on the request.
                        //For PirateQuesting this was preferred over the date on the user's machine
			var date = Date.parse(request.getResponseHeader("Date"));

                        //Again a PQ specific function call, but left as an example.
                        //This just passes a string URL, the text of the response,
                        //the date, and the data in the POST request (if applicable)
			piratequesting.ProcessRawResponse(request.originalURI.spec,
                                               responseSource,
                                               date,
                                               data);
		}
	}
	catch (e)
	{
		//standard function to dump a formatted version of the error to console
		dumpError(e);
	}
	//Pass it on down the chain
	this.originalListener.onStopRequest(request,
                                         context,
                                         statusCode);
    },</code></pre>
<p>The <code>onStopRequest</code> above has a few tricky parts. The first is the <code>QueryInterface</code> to <a href="http://www.oxymoronical.com/experiments/apidocs/interface/nsIHttpChannel"><code>nsIHttpChannel</code> </a>&#8211; this is critical to getting the info needed. The second tricky part is to get the posted variables. To do so, you need to check that the <code>requestMethod</code> was indeed post, and then we call <code>readPostTextFromRequest</code> which I&#8217;ll introduce in a bit. The last tricky bit is getting the Date header from the response. <code>Date.parse()</code> plays nicely with those (assuming the server response conforms)</p>
<pre><code class='javascript'>    QueryInterface: function (aIID) {
        if (aIID.equals(Ci.nsIStreamListener) ||
            aIID.equals(Ci.nsISupports)) {
            return this;
        }
        throw Components.results.NS_NOINTERFACE;
    },</code></pre>
<p>This is pretty standard for anything fulfilling an interface contract for Firefox (or other mozilla-based browsers). <code>QueryInterface</code> is part of the <a href="http://www.oxymoronical.com/experiments/apidocs/interface/nsISupports"><code>nsISupports</code></a> interface and is the only part which is scriptable. All interfaces are derived from <code>nsISupports</code>, so it has to be there.
</li>
<li>
<h5>Utility methods</h5>
<p>The following methods are required by our TracingListener but are not part of the interface contract. (It would also have been possible to define them globally or within a pseudo-namespace.)</p>
<pre><code class='javascript'>    readPostTextFromRequest : function(request, context) {
        try
        {
	        var is = request.QueryInterface(Ci.nsIUploadChannel).uploadStream;
	        if (is)
	        {
	            var ss = is.QueryInterface(Ci.nsISeekableStream);
	            var prevOffset;
	            if (ss)
	            {
	                prevOffset = ss.tell();
	                ss.seek(Ci.nsISeekableStream.NS_SEEK_SET, 0);
	            }

	            // Read data from the stream..
		    var charset = "UTF-8";
		    var text = this.readFromStream(is, charset, true);

	            if (ss &amp;&amp; prevOffset == 0)
	                ss.seek(Ci.nsISeekableStream.NS_SEEK_SET, 0);

	            return text;
	        }
		else {
			dump("Failed to Query Interface for upload stream.\n");
		}
	    }
	    catch(exc)
	    {
			dumpError(exc);
	    }

	    return null;
	},</code></pre>
<p>I will readily admit that <code>readPostTextFromRequest</code> is mostly taken from Firebug, though there are a few changes. Basically, we have to do the same thing as before and <code>QueryInterface</code> into the appropriate interface. In this case we need <a href="http://www.oxymoronical.com/experiments/apidocs/interface/nsIUploadChannel">nsIUploadChannel</a> to get access to <code>uploadStream</code>. And then we <code>QueryInterface</code> the <code>uploadStream</code> into a <a href="http://www.oxymoronical.com/experiments/apidocs/interface/nsISeekableStream">nsISeekableStream</a> (noticing a pattern, yet? <code>QueryInterface</code> is your best friend.. and worst enemy.). After that we store the original offset in the stream in <code>prevOffset</code>, and then seek to the beginning of the stream. Then we read the data and, if the stream was at position 0 originally, we seek to the beginning again.</p>
<pre><code class='javascript'>	readFromStream : function(stream, charset, noClose)	{

	    var sis = CCSV("@mozilla.org/binaryinputstream;1",
                            "nsIBinaryInputStream");
	    sis.setInputStream(stream);

	    var segments = [];
	    for (var count = stream.available(); count; count = stream.available())
	        segments.push(sis.readBytes(count));

	    if (!noClose)
	        sis.close();

	    var text = segments.join("");
	    return text;
	}

}</code></pre>
<p><code>readFromStream</code> is also largely from Firebug with a few modifications. It is however remarkably similar to what is done in <code>onDataAvailable</code> and <code>onStopRequest</code>. Basically, we get a <code>BinaryInputStream</code> to work with the stream given. Then we loop through the segments of the stream (size provided by <code>available()</code>) and add them to an array. When finished with that, we join the segments and return the text.</p>
<pre><code class='javascript'>httpRequestObserver = {

	observe: function(request, aTopic, aData){
		if (typeof Cc == "undefined") {
			var Cc = Components.classes;
		}
		if (typeof Ci == "undefined") {
			var Ci = Components.interfaces;
		}
	    	if (aTopic == "http-on-examine-response") {
	    		request.QueryInterface(Ci.nsIHttpChannel);

			if (request.originalURI
                            &amp;&amp; piratequesting.baseURL == request.originalURI.prePath
                            &amp;&amp; request.originalURI.path.indexOf("/index.php?ajax=") == 0) {
				var newListener = new TracingListener();
    				request.QueryInterface(Ci.nsITraceableChannel);
    				newListener.originalListener = request.setNewListener(newListener);
			}
		}
	},

	QueryInterface: function(aIID){
		if (typeof Cc == "undefined") {
			var Cc = Components.classes;
		}
		if (typeof Ci == "undefined") {
			var Ci = Components.interfaces;
		}
		if (aIID.equals(Ci.nsIObserver) ||
		aIID.equals(Ci.nsISupports)) {
			return this;
		}

		throw Components.results.NS_NOINTERFACE;

	},
};</code></pre>
<p>This part is fairly straightforward. The object httpRequestObserver has to fulfill the contract for the nsIObserver interface &#8212; which only has two methods: observe and QueryInterface.
</li>
</ul>
</li>
</ul>
</li>
<li>
<h3>Observer registration</h3>
<p>Finally, we need to register the observer:</p>
<pre><code class='javascript'>var observerService = Cc["@mozilla.org/observer-service;1"]
    .getService(Ci.nsIObserverService);

observerService.addObserver(httpRequestObserver,
    "http-on-examine-response", false);</code></pre>
<p>Now the <a href="http://www.oxymoronical.com/experiments/apidocs/interface/nsIObserverService"><code>observerService</code></a> will call the <code>observe</code> method on <code>httpRequestObserver</code> whenever it notifies observers with the <code>http-on-examine-response</code> topic.</p>
<p>When you want to unregister the observer, use:</p>
<pre><code class='javascript'>observerService.removeObserver(httpRequestObserver,
    "http-on-examine-response");</code></pre>
<p>As you can see, getting the text and post variables from an http request is non-trivial.
</li>
</ul>
<p>Note, though, that this code does not check the context to determine whether the http request is <em>for</em> a browser window, or <em>from</em> a browser window so depending on the complexity of your situation, you may want to do that as well. Perhaps, I&#8217;ll add that in another post.</p>
<p>(See Firebug license <a href="http://code.google.com/p/fbug/source/browse/branches/firebug1.5/license.txt">here</a>. Special thanks to the Firebug team and to Jon Odvarko for providing so much useful material. The interface docs at <a href="http://www.oxymoronical.com/experiments/apidocs/platform/1.9.2a1pre">oxymoronical</a> are a great resource. The <a href="https://developer.mozilla.org">Mozilla Developer Center</a> also deserves special credit for great documentation. )</p>
<p><strong>Update (Jan 17, 2010):</strong> Corrected a small bug in <code>onStopRequest</code> (Thanks Broady!). See <a href="http://www.ashita.org/howto-xhr-listening-by-a-firefox-addon/#comment-419">below</a> for details.</p>
<p><strong>Update (April 22, 2010):</strong> Corrected a bug which doesn&#8217;t occur if Firebug is installed (Thanks Harini!). See <a href="http://www.ashita.org/howto-xhr-listening-by-a-firefox-addon/#comment-1125">below</a> for details.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.ashita.org/howto-xhr-listening-by-a-firefox-addon/feed/</wfw:commentRss>
		<slash:comments>22</slash:comments>
		</item>
		<item>
		<title>Implementing an XPCOM Firefox Interface and Creating Observers</title>
		<link>http://www.ashita.org/implementing-an-xpcom-firefox-interface-and-creating-observers/</link>
		<comments>http://www.ashita.org/implementing-an-xpcom-firefox-interface-and-creating-observers/#comments</comments>
		<pubDate>Thu, 08 Oct 2009 19:05:25 +0000</pubDate>
		<dc:creator>Jonathan Fingland</dc:creator>
				<category><![CDATA[Firefox]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Firefox Extension]]></category>
		<category><![CDATA[XPCOM]]></category>

		<guid isPermaLink="false">http://ashita.org/?p=314</guid>
		<description><![CDATA[There are lots of cases when it is desirable to implement one of the XPCOM interfaces in use by Firefox, or other mozilla-based browsers. There are three cases where PirateQuesting does so, but once you see the concept, it should be easy to adapt to your situation.


You must have a QueryInterface to enjoy this ride
First [...]]]></description>
			<content:encoded><![CDATA[<p>There are lots of cases when it is desirable to implement one of the XPCOM interfaces in use by Firefox, or other mozilla-based browsers. There are three cases where PirateQuesting does so, but once you see the concept, it should be easy to adapt to your situation.</p>
<ul class='structure'>
<li>
<h3>You must have a QueryInterface to enjoy this ride</h3>
<p>First off, all XPCOM interfaces in Firefox inherit from <a href="https://developer.mozilla.org/en/nsISupports"><code>nsISupports</code></a> (Also see details on oxymoronical.com <a href="http://www.oxymoronical.com/experiments/apidocs/platform/1.9.2a1pre/interface/nsISupports">here</a>). Only one method is scriptable and part of XPCOM &#8212; <a href="https://developer.mozilla.org/en/NsISupports/QueryInterface"><code>QueryInterface</code></a> &#8212; and it <em>must</em> be present in all implementations of XPCOM interfaces. </p>
<pre><code class='javascript'>
//"implements" nsISupports
var InterfaceImplementation = function() {
  QueryInterface: function (aIID) {
      if (aIID.equals(Components.interfaces.nsISupports))
      {
         return this;
      }
      throw Components.results.NS_NOINTERFACE;
  }
}
</code></pre>
<p>The above is an example of the very minimum required to support any interface. <code>QueryInterface</code> requires a first parameter which is an aIID from <code>Components.interfaces.*</code>. There is also a second, optional, parameter, but as I have never come across this in use, it&#8217;s not worth pursuing here.
</li>
<li>
<h3>Now what?</h3>
<p>A very common (and useful) use of XPCOM interface implementation is creating your own observers, for example:</p>
<pre><code class='javascript'>
var myObserver = {

  observe: function(request, aTopic, aData){
    if (aTopic == "http-on-examine-response")
    {
      //response has come back, now what?
    }
    else if (aTopic == "http-on-modify-request")
    {
      //opportunity to modify headers on request
    }
  },

  QueryInterface: function(aIID){
     if (aIID.equals(Components.interfaces.nsIObserver) ||
         aIID.equals(Components.interfaces.nsISupports))
    {
      return this;
    }
    throw Components.results.NS_NOINTERFACE;
  },
};
</code></pre>
<p>The <a href="http://www.oxymoronical.com/experiments/apidocs/interface/nsIObserverService">nsIObserver</a> interface is fairly simple as it only adds one new method. As you can see now, though, <code>QueryInterface</code> now checks for both <code>nsIObserver</code> and <code>nsISupports</code>. Remember: any interface you implement must have a <code>QueryInterface</code> supporting all interfaces in the inheritance chain.
</li>
<li>
<h3>Observer registration</h3>
<p>If you then wanted to register your observer, it&#8217;s as easy as:</p>
<pre><code class='javascript'>
var observerService = Components.classes["@mozilla.org/observer-service;1"]
                               .getService(Components.interfaces.nsIObserverService);

observerService.addObserver(myObserver,"http-on-examine-response", false);
observerService.addObserver(myObserver,"http-on-modify-request", false);
</code></pre>
<p>Then to unregister, you do:</p>
<pre><code class='javascript'>
observerService.removeObserver(myObserver, "http-on-examine-response");
observerService.removeObserver(myObserver, "http-on-modify-request");
</code></pre>
<p>When I have a chance, I&#8217;ll add a more complete example of using observers to watch http requests, but in the meantime check out the list of <a href="https://developer.mozilla.org/en/Observer_Notifications">Observer Notifications</a> at MDC.
</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.ashita.org/implementing-an-xpcom-firefox-interface-and-creating-observers/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Singletons in JavaScript</title>
		<link>http://www.ashita.org/singletons-in-javascript/</link>
		<comments>http://www.ashita.org/singletons-in-javascript/#comments</comments>
		<pubDate>Thu, 24 Sep 2009 07:13:57 +0000</pubDate>
		<dc:creator>Jonathan Fingland</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[closures]]></category>
		<category><![CDATA[Singleton]]></category>

		<guid isPermaLink="false">http://ashita.org/?p=329</guid>
		<description><![CDATA[I use singletons all over the PirateQuesting code, but I&#8217;ve never explained the idea here, nor how they are different from singletons in other languages.
Anyone familiar with common design patterns knows how singletons work in the vast majority of languages.  For a PHP example, see this post. 
In JavaScript there are basically two main [...]]]></description>
			<content:encoded><![CDATA[<p>I use singletons all over the <a href="http://pq.ashita.org">PirateQuesting</a> code, but I&#8217;ve never explained the idea here, nor how they are different from singletons in other languages.</p>
<p>Anyone familiar with common design patterns knows how singletons work in the vast majority of languages.  For a PHP example, see <a href="http://www.ashita.org/singletons-in-php/">this post</a>. </p>
<p>In JavaScript there are basically two main ways to create a singleton. One is use immediate instantiation so that the class may not be instantiated again. The second is closer to the traditional singleton pattern, however, since there are no private members or constructors, we can get around this by using a nested &#8216;class&#8217; constructor &#8212; and there are two ways to accomplish this.</p>
<p>The first way is done as follows:</p>
<pre>
var singleton = new (function Singleton() {
                               this.value = 12;
                             } )();

alert(singleton.value); // alerts 12;

var singly = new Singleton(); // Singleton is not defined.

alert(singleton instanceof Singleton); // Singleton is not defined
</pre>
<p>In the above, the constructor name, Singleton, isn&#8217;t really necessary. While it can&#8217;t be used to instantiate the Singleton again, it also can&#8217;t be used with <code>instanceof </code>or <code>typeof</code> so feel free to leave it out if you want; leaving it in, does make it more obvious what is happening though.</p>
<p>And the second way (version 1):</p>
<pre>
var Singleton = (function () {
  var instance = null;

  function Singleton() {
    this.value = 12;
  }

  this.getInstance = function () {
    if (instance === null) {
      instance = new Singleton();
    }
    return instance;
  }
})();

var singleton = Singleton.getInstance();
alert(singleton.value); // alerts 12;

var singly = new Singleton(); // Singleton is not a construct

alert(singleton instanceof Singleton); //invalid 'instanceof' operand Singleton
</pre>
<p>The above is just an anonymous function being called immediately (note the <code>()</code> after the function declaration). Inside the function it declares a pseudo-private member called <code>instance</code>, a pseudo-private constructor, <code>Singleton</code>, and a <code>getInstance</code> method. The <code>getInstance</code> method can see <code>instance</code> due to closure, while the outside world has no idea that it exists.</p>
<p>And finally, the second way (version 2):</p>
<pre>
var Singleton = {

  getInstance : (function() {

    var instance;
    function Singleton() {
      this.value = 12;
    }

    return function () {
      if (instance == null) {
	    instance = new Singleton();
      }
      return instance;

    }

  })()
}

var singleton = Singleton.getInstance();
alert(singleton.value);

var singly = new Singleton(); // Singleton is not a constructor

alert(singleton instanceof Singleton); //invalid 'instanceof' operand Singleton
</pre>
<p>In this final example, all of the logic is put into the <code>getInstance</code> function which is the result of a self-calling function which itself returns a function. Yeah, it&#8217;s a little hard to follow, but basically the returned function has visibility of <code>instance </code>and the <code>Singleton </code>constructor due to closure.</p>
<p>As a closing note, it&#8217;s worth pointing out that although all of the above methods do not permit a second instance construction, they also do not allow use of <code>typeof </code>or <code>instanceof </code>for type verification.</p>
<h3>Update</h3>
<p>Based on a comment below by Peter Robinett, I&#8217;ve come up with a different way to do this, which allows for <code>instanceof</code> and <code>typeof</code> and seems to be an all-round good solution to the problem. It does not, however use the classical <code>getInstance</code> method, but works well all the same.</p>
<pre>
var Singleton = function () {
  var instantiated = false;

  return function () {
    if (instantiated) {
      throw "Singleton already instantiated";
    }
    instantiated = true;
    this.value=12;
    }
}()

var singleton = new Singleton();
alert(singleton.value);    //alerts 12
alert(singleton instanceof Singleton);  alerts true 

var singly = new Singelton(); //throws exception and cannot be instantiated
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.ashita.org/singletons-in-javascript/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Singletons in PHP</title>
		<link>http://www.ashita.org/singletons-in-php/</link>
		<comments>http://www.ashita.org/singletons-in-php/#comments</comments>
		<pubDate>Wed, 23 Sep 2009 02:59:09 +0000</pubDate>
		<dc:creator>Jonathan Fingland</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[Singleton]]></category>

		<guid isPermaLink="false">http://ashita.org/?p=331</guid>
		<description><![CDATA[I write PHP regularly in my job, but this is the first post on Ashita.org on a PHP subject. One interesting problem recently was how to make Singletons in PHP from a generic base class and extended where necessary. First, an introduction: Singletons are an incredibly common and useful design pattern. Singletons are used to [...]]]></description>
			<content:encoded><![CDATA[<p>I write PHP regularly in my job, but this is the first post on Ashita.org on a PHP subject. One interesting problem recently was how to make Singletons in PHP from a generic base class and extended where necessary. First, an introduction: Singletons are an incredibly common and useful design pattern. Singletons are used to ensure there is only one instance of a class and the class cannot be instantiated directly from outside the class.</p>
<ul class='structure'>
<li>
<h3>Simple Case</h3>
<p>In PHP, the singleton pattern is as easy as making a class with a private or protected constructor and a static method to get the single instance.</p>
<pre><code class='javascript'>
class Singleton
{
  private $instance;

  private function __construct()
  {
  }

  private function __clone()
  {
    //do nothing
  }

  public static function getInstance()
  {
    if (is_null(self::$instance))
    {
      self::$instance = new self();
    }
    return self::$instance;
  }
}</code>
</pre>
<ul class='structure'>
<li>
<h4>Note</h4>
<p>One thing to note about the code above is the <code>__clone()</code> method. Unless overridden, the default __clone() method creates a new object with all of the properties copied over. Obviously, this goes against the principles of a singleton &#8212; there should be only one instance.
</li>
</ul>
<p>This technique allows the class author to ensure only one instance is available and that any changes made to it are shared by all references to this object, but what if we wanted to use this pattern more than once. Wouldn&#8217;t it be better to extend this class? Doing so would require some changes&#8230; (and in this implementation, it requires php 5.3 or higher)
</li>
<li>
<h3>Extendable Singleton</h3>
<pre><code class='javascript'>
abstract class Singleton
{
  public static function getInstance()
  {
    $class = get_called_class();
    if (is_null($class::$instance))
    {
      $class::$instance = new $class();
    }
    return $class::$instance;
  }

}

class Database extends Singleton
{

  protected static $instance;

  protected function __construct()
  {
    //do DB init work here
  }

  private function __clone()
  { }

  //include functions to act on DB here

}
</code></pre>
<p>basically, the only thing classes extending Singleton would need to do is mark their <code>__construct </code>method protected, their <code>__clone</code> method can remain private, and to include a <code>protected static $instance</code> class variable. Further simplifications <em>could</em> be made, but it seems a good base to work from. (Note that the above example requires a somewhat quirky behaviour in php that allows subclasses to inherit static methods.)
</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.ashita.org/singletons-in-php/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Prototype&#8217;s Bind and Curry</title>
		<link>http://www.ashita.org/prototypes-bind-and-curry/</link>
		<comments>http://www.ashita.org/prototypes-bind-and-curry/#comments</comments>
		<pubDate>Mon, 20 Apr 2009 12:58:02 +0000</pubDate>
		<dc:creator>Jonathan Fingland</dc:creator>
				<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://ashita.org/?p=282</guid>
		<description><![CDATA[I&#8217;ve been a fan of both Prototype and JQuery for a while and have no qualms recommending either. They do have somewhat different aims, and as such it&#8217;s a good idea to consider carefully which one best meets the needs of your project (or if you even need either to meet your needs). I&#8217;ll leave [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been a fan of both Prototype and JQuery for a while and have no qualms recommending either. They do have somewhat different aims, and as such it&#8217;s a good idea to consider carefully which one best meets the needs of your project (or if you even need either to meet your needs). I&#8217;ll leave that discussion for another post, though. </p>
<p>Today, I&#8217;m gonna show you two very useful functions in prototype. Show you how to use them, and show you how they work.</p>
<p>First off, <code>curry</code> with a quick example:</p>
<pre>
function show_name(name)
{
    alert(name);
}

var show_my_name = show_name.curry("Jon");
show_my_name();
</pre>
<p>The call to <code>show_my_name</code> will result in an alert dialog with &#8220;Jon&#8221;. The curry function allowed me to pre-load the parameters. You can also do a partial curry as follows:</p>
<pre>
function show_animal(animal_type,adjective)
{
    alert("It is a " + adjective + " " + animal_type);
}

var show_dog = show_animal.curry("dog");

show_dog("fast");
show_dog("brown");
</pre>
<p>The above will result in two alert dialogs &#8212; the first saying &#8220;It is a fast dog&#8221; and the second saying &#8220;It is a brown dog&#8221;. the <code>show_dog</code> method only required the one parameter, because the animal type had already been pre-loaded.</p>
<p>Bind works in an almost identical way but with one important difference &#8212; context switching. The first parameter to <code>bind</code> is the desired context. For example:</p>
<pre>
var fancy_box = function(element)
{
     //ensure element is a checkbox. if not, bail
     if ((!(element instanceof HTMLElement)
         || !(element.nodeName.toLowerCase() === "input")
         || !(element.getAttribute("type").toLowerCase()  === "checkbox"))
    {
         return;
    }

    this.isChecked = function()
    {
        return !!element.checked;
    }

    this.click_handler = function()
    {
        var message = this.isChecked() ? "Checked" : "Not Checked";
        alert(message);
    }

    element.observe("click", this.click_handler.bind(this)); //observe is a prototype stand-in for addEventListener/attachEvent to allow you to ignore browser differences.
}
</pre>
<p>The <code>element.observe</code> line above makes use of bind to ensure the click_handler is working in the correct context. You can, however, use a different context instead.</p>
<p>Event handlers can be tricky and there is actually a specialized version of <code>bind</code>, called <code>bindAsEventListener</code> which works the same as bind, but also passes the event. </p>
<hr/>
<p>So&#8230;. How do they work? Well, both curry and bind (okay, and bindAsEventListener, too) rely on built in JavaScript methods <code><a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Function/call">call</a></code> and <code><a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Function/apply">apply</a></code>.</p>
<p><code>call</code> and <code>apply</apply> are <em>very</em> similar and really only differ in one significant way. Both take the operating context as the first parameter but <code>apply</code> takes the arguments as an array whereas <code>call</call> takes the arguments as regular parameters.</p>
<p>To use an earlier example:</p>
<pre>
show_name.call(window,"Bob");
</pre>
<p>This will result in show_name operating in the window context and being given the parameter "Bob". This can be especially important when you use these methods on objects which don't natively support them, though.</p>
<p>Every function has a special variable called <code>arguments</code> which is <em>like</em> an array but isn't. It's array like behavior, though, makes the Array functions usable on it as in the following:</p>
<pre>
function say()
{
var message = Array.prototype.join.call(arguments," ");
alert(message);
}
say("Hello","Bob");
</pre>
<p>Even though the function <code>say()</code> doesn't explicitly take any arguments, what it really does is take a variable number of arguments, and joins them together, separated by spaces, and then alerts them. This kind of technique can be quite handy in lots of situations, but in this post, I'm concerned about how it will help us understand <code>bind</code> and <code>curry</code>.</p>
<p>From Prototype 1.6.1:</p>
<pre>
Object.extend(Function.prototype, (function() {
  var slice = Array.prototype.slice;

  function update(array, args) {
    var arrayLength = array.length, length = args.length;
    while (length--) array[arrayLength + length] = args[length];
    return array;
  }

  function merge(array, args) {
    array = slice.call(array, 0);
    return update(array, args);
  }

  function bind(context) {
    if (arguments.length < 2 &#038;&#038; Object.isUndefined(arguments[0])) return this;
    var __method = this, args = slice.call(arguments, 1);
    return function() {
      var a = merge(args, arguments);
      return __method.apply(context, a);
    }
  }

  function bindAsEventListener(context) {
    var __method = this, args = slice.call(arguments, 1);
    return function(event) {
      var a = update([event || window.event], args);
      return __method.apply(context, a);
    }
  }

  function curry() {
    if (!arguments.length) return this;
    var __method = this, args = slice.call(arguments, 0);
    return function() {
      var a = merge(args, arguments);
      return __method.apply(this, a);
    }
  }

//...trimmed
}
</pre>
<p>First lets look at curry again.</p>
<pre>
    if (!arguments.length) return this;
</pre>
<p>This just means we should bail if there are no arguments and simply return the original function.</p>
<pre>
    var __method = this, args = slice.call(arguments, 0);
</pre>
<p>Two things are being done here. First, <code>__method</code> is storing a reference to <code>this</code> for later use. This allows us to make use of a closure in the following anonymous function. The second thing is a <code>call</code> using <code>Array.prototype.slice</code> (though shortened by prototype for reuse) which allows us to convert the arguments object into an array. Handy.</p>
<pre>
    return function() {
</pre>
<p>Here we return an anonymous function. This is how <code><em>function</em>.curry(<em>parameter</em>)</code> returns a function we can use later, for example, in an event handler or other callback situation.</p>
<pre>
      var a = merge(args, arguments);
</pre>
<p>This is a fairly straightforward to read. The variable <code>a</code> contains a merged array of <code>args</code> and <code>arguments</code>. <code>args</code> is available via a technique known as closure. <code>args</code>, declared in the wrapping function is visible to, or within scope of, the anonymous function being returned. If you're unsure what the functions <code>merge</code> and <code>update</code> do, just know that <code>merge</code> simply converts the first parameter to an array and calls <code>update</code>. <code>update</code> then loops through <code>args</code> and appends each element to <code>arguments</code> (<code>array</code> in the update function). </p>
<pre>
      return __method.apply(this, a);
</pre>
<p>Finally, our anonymous function returns the value from the original method, with the combined arguments of the original call to curry, and the arguments passed to the anonymous function when it was called.</p>
<p>Whew.</p>
<p>Still with me?</p>
<p>Okay, lets go.</p>
<p>Bind is a little more complicated, but not much, and if you understand curry, this shouldn't be much of a problem.</p>
<pre>
  function bind(context) {
    if (arguments.length < 2 &#038;&#038; Object.isUndefined(arguments[0])) return this;
</pre>
<p>First important difference: bind requires a context parameter. If the first argument is undefined and there is fewer than two parameters, then there really isn't anything to be done, and <code>bind</code> simply returns the original function.</p>
<pre>
    var __method = this, args = slice.call(arguments, 1);
</pre>
<p>This is virtually identical to curry, except that instead of converting the entire arguments array, we only want the second element onwards.</p>
<pre>
    return function() {
      var a = merge(args, arguments);
</pre>
<p>Same as curry.</p>
<pre>
      return __method.apply(context, a);
</pre>
<p>Slightly different from curry again. Instead of <code>this</code>, <code>bind</code> uses <code>apply</code> with a <em>context</em>. </p>
<p>For more examples on Prototype extensions to the Function prototype, see <a href="http://api.prototypejs.org/language/function.html">http://api.prototypejs.org/language/function.html</a></p>
<hr/>
<p>For those familiar with closures, you may think this is totally unnecessary -- and you may be right -- if you only need to make use of this once or twice in your web app, but if you frequently find yourself needing closures just to refer to <code>this</code> then maybe it's worth generalizing into a routine, or going with a framework that has it built in. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.ashita.org/prototypes-bind-and-curry/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>JavaScript&#8217;s default operator</title>
		<link>http://www.ashita.org/javascripts-default-operator/</link>
		<comments>http://www.ashita.org/javascripts-default-operator/#comments</comments>
		<pubDate>Thu, 02 Apr 2009 11:30:30 +0000</pubDate>
		<dc:creator>Jonathan Fingland</dc:creator>
				<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://ashita.org/?p=278</guid>
		<description><![CDATA[Here&#8217;s something pretty easy to use, useful, and strangely not as common as you would expect.
JavaScript has an operator known as the &#8220;default&#8221; operator and is the same as the logical-or operator. That&#8217;s right. &#124;&#124;.
First, some examples of how we can use it:
var value_1 = false &#124;&#124; 2;
var value_2 = null &#124;&#124; 2;
var value_3 = [...]]]></description>
			<content:encoded><![CDATA[<p>Here&#8217;s something pretty easy to use, useful, and strangely not as common as you would expect.</p>
<p>JavaScript has an operator known as the &#8220;default&#8221; operator and is the same as the logical-or operator. That&#8217;s right. <code>||</code>.</p>
<p>First, some examples of how we can use it:</p>
<pre>var value_1 = false || 2;
var value_2 = null || 2;
var value_3 = 0 || 2;</pre>
<p>In all three of the above cases, the left side of the default operator is falsey and thus <code>value_1</code>, <code>value_2</code>, and <code>value_3</code> are all equal to 2. Just to make it clear, falsey values are values which can be converted to boolean false. &#8216;false&#8217; itself is a given, null is considered false, so are empty strings and finally and so is 0. Negative numbers are <em>not</em> false and nor are objects, empty or otherwise. Thus:</p>
<table border="0">
<tbody>
<tr>
<th>Truthy values</th>
<th>Falsey Values</th>
</tr>
<tr>
<td>
<ul>
<li>Non-zero number</li>
<li>Object</li>
<li>Boolean true</li>
<li>Non-empty string</li>
</ul>
</td>
<td>
<ul>
<li>Zero (0)</li>
<li>Null</li>
<li>Boolean false</li>
<li>Empty string</li>
</ul>
</td>
</tr>
</tbody>
</table>
<p>Below is a slightly more useful example. I&#8217;ve used jQuery&#8217;s <code>$.get</code> here to simplify the example and the <code>display_items</code> method is left to the imagination of the reader.</p>
<pre>var DEFAULT_ITEM_LIMIT = 20; //In the case of a firefox extension, this would be better written as: const DEFAULT_ITEM_LIMIT = 20;

function get_random_items(how_many)
{
     how_many = how_many || DEFAULT_ITEM_LIMIT;
     $.get("random_items.php", {limit:how_many}, display_items);
}</pre>
<p>In the above example, we see a reasonable default being set in advance and if the get_random_items method is called without passing parameters, or provided null, false, 0 or an empty string as the value of how_many, then the default item limit will be used instead.</p>
<p>It works pretty simply. If the statement on the left side is falsey, then the value on the right side is used instead &#8212; exactly like the logical-or. See this <a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Logical_Operators#Logical_OR_%28.7c.7c%29">MDC page on logical operators</a> for more examples.</p>
<p>Now you <em>can</em> do some fancy things with this. For example, you <em>could</em> do something like this:</p>
<pre>var user_name;
if ((user_name = (prompt("What is your name?") || "Jon")) === "Jon")
{
    //do stuff
}</pre>
<p>But please, please don&#8217;t. That line was painful to write, and unnecessarily difficult to read. Something like:</p>
<pre>var user_name = prompt("What is your name?");
if (!user_name)
{
    //no name provided, use default
    user_name = "Jon";
}</pre>
<p>&#8230; would be much better. Just remember, like most coding tricks, only use the default operator when it makes things <em>more</em> readable.</p>
<p>One of the most common, and useful examples of this technique comes with event handlers.</p>
<pre>
function box_click_handler(event)
{
    event = event || window.event;
    var target = event.target || event.srcElement;
    //do other stuff
}
</pre>
<p>Basically, by using the default operator we were able to quickly and easily get the event object and the target (or source) of the event in both cases: browsers that have strong DOM spec support, and browsers that don&#8217;t, i.e. IE. </p>
<p>As a closing note, just like the logical-or in a conditional, this too can be chained. The leftmost truthy value will be used.</p>
<pre>
function find_user(name)
{
    name = name || false || get_default_name();
    $.post("find_user.php", {name:name}, display_user);
}
</pre>
<p>Of course the above is needlessly long (the false is just thrown in for demonstration purposes), but I think you get the idea. Hope ya&#8217;ll find it useful. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.ashita.org/javascripts-default-operator/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The loadOverlay Dilemma</title>
		<link>http://www.ashita.org/the-loadoverlay-dilemma/</link>
		<comments>http://www.ashita.org/the-loadoverlay-dilemma/#comments</comments>
		<pubDate>Wed, 25 Mar 2009 04:51:41 +0000</pubDate>
		<dc:creator>Jonathan Fingland</dc:creator>
				<category><![CDATA[Firefox]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Pirate Questing]]></category>
		<category><![CDATA[XUL]]></category>

		<guid isPermaLink="false">http://ashita.org/?p=256</guid>
		<description><![CDATA[When making Firefox extensions with modular components, it&#8217;s nice to be able to include overlays based on preferences or some other criteria at loadtime. One of the problems that quickly comes up is that sequential loadOverlay calls will fail. This bug is documented here. The solution described there, and elsewhere, is to use chained observers [...]]]></description>
			<content:encoded><![CDATA[<p>When making Firefox extensions with modular components, it&#8217;s nice to be able to include overlays based on preferences or some other criteria at loadtime. One of the problems that quickly comes up is that sequential loadOverlay calls will fail. This bug is documented <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=330458">here</a>. The solution described there, and elsewhere, is to use chained observers and a custom queue. Strangely, I never came across an implementation example of such an observer/queue combination. So&#8230; with that stunning introduction, I give you the system used in PirateQuesting 2.</p>
<p>The first part here is an overlay registry. Essentially, the queue portion of the solution.</p>
<pre>
piratequesting.overlayRegistry = function() {
	var overlays = [];
	var index = 0;

	function conflicts(tabid, tabpanelid, overlayFile) {
		for (var i = 0, len = overlays.length; i&lt;len;++i)
			if ((tabid == overlays[i].getTabId() &#038;&#038; tabid != null )  || (tabpanelid == overlays[i].getTabPanelId() &#038;&#038; tabpanelid != null) || overlayFile == overlays[i].getOverlayFile())
				return true;
		return false;
	}

	function overlay(tabid, tabpanelid, overlayFile) {
		var tabid = tabid;
		var tabpanelid = tabpanelid;
		var overlayFile = overlayFile;
		var added = false;

		return {
			toString : function() {
				return "tabid: " + tabid + "\ntabpanelid: " + tabpanelid
						+ "\noverlayFile: " + overlayFile;
			},
			getTabId : function() {
				return tabid;
			},
			getTabPanelId : function() {
				return tabpanelid;
			},
			getOverlayFile : function() {
				return overlayFile;
			},
			getAdded : function() {
				return added;
			},
			setAdded : function(val) {
				added = !!val; // ensure boolean
			}
		}

	}

	return {
		addOverlay : function(tabid, tabpanelid, stringFile) {
			if (!conflicts(tabid, tabpanelid, stringFile))
				overlays.push(new overlay(tabid, tabpanelid, stringFile));
			else
				dump("\nOverlay conflict occurred on: " + tabid + ", " + tabpanelid + ", " + stringFile);
		},
		getOverlayByIndex : function(index) {
			return overlays[index];
		},
		getOverlayByTabId : function(tabid) {
			var ol = overlays.length;
			for (var i = 0; i &lt; ol; i++) {
				if (overlays[i].getTabId() == tabid)
					return overlays[i];
			}
			return false;
		},
		count : function() {
			return overlays.length;
		},
		reset : function() {
			index = 0;
		},
		next : function() {
			if (index &lt; overlays.length) {
				return overlays[index++];
			} else
				return null;
		},
		progress : function() {
			return Math.ceil(index * 100 / overlays.length);
		},
		resetAll : function() {
			this.reset();
			var nex;
			while (nex = this.next()) {
				nex.setAdded(false);
			}
			this.reset();
		}

	}
}();
</pre>
<p>Now, that is a somewhat specialized case. The tabid and tabpanelid are arguably unnecessary but have been included to prevent two modules having the same tab ids, and, more importantly, to be able to refer to the overlay by a known value, in this case the tabid.</p>
<p>A somewhat stripped down version might look like:</p>
<pre>
var overlayRegistry = function() {
	var overlays = [];
	var index = 0;

	function conflicts(overlayFile) {
		for (var i = 0, len = overlays.length; i&lt;len;++i)
			if (overlayFile == overlays[i].getOverlayFile())
				return true;
		return false;
	}

	function overlay(overlayFile) {
		var overlayFile = overlayFile;
		var added = false;

		return {
			toString : function() {
				return "\noverlayFile: " + overlayFile;
			},
			getOverlayFile : function() {
				return overlayFile;
			},
			getAdded : function() {
				return added;
			},
			setAdded : function(val) {
				added = !!val; // ensure boolean
			}
		}

	}

	return {
		addOverlay : function(stringFile) {
			if (!conflicts(stringFile))
				overlays.push(new overlay(stringFile));
			else
				dump("\nOverlay conflict occurred on: " + stringFile);
		},
		getOverlayByIndex : function(index) {
			return overlays[index];
		},
		count : function() {
			return overlays.length;
		},
		reset : function() {
			index = 0;
		},
		next : function() {
			if (index &lt; overlays.length) {
				return overlays[index++];
			} else
				return null;
		},
		progress : function() {
			return Math.ceil(index * 100 / overlays.length);
		},
		resetAll : function() {
			this.reset();
			var nex;
			while (nex = this.next()) {
				nex.setAdded(false);
			}
			this.reset();
		}

	}
}();
</pre>
<p>The overlay registry is simply an iterator-style queue. This makes walking through the items very easy for the observer (shown next) which doesn&#8217;t (and shouldn&#8217;t) really have any idea of the state of the queue. The queue, overlayRegistry, makes a number of methods available for getting basic info about the queue (size, progress, etc) for use in progress bars or the like. It also provides ways of resetting the queue. Obviously, since it&#8217;s designed to be an iterator, there are ways of getting the next item and advancing the queue. </p>
<p>The second part of the solution is using a chained observer. Again, the piratequesting implementation is:</p>
<pre>
function overlayObserver()
{
  this.register();
}
overlayObserver.prototype = {
  observe: function(subject, topic, data) {

  	function cleanUp() {
		sidebar.contentDocument.getElementById("pqmain_deck").selectedIndex="1";

		var mod_boxes = sidebar.contentDocument.getElementsByTagName("tabbox");
		for (var i=0,len=mod_boxes.length;i&lt;len;++i) {
			if (hasClassName(mod_boxes[i],"moduleBox")) {
				mod_boxes[i].selectedIndex = 0;
			}
		}
  	}

  	if (topic == "xul-overlay-merged") {
		try {
			var nex = piratequesting.overlayRegistry.next();
			if (nex) {
  				sidebar.contentDocument.getElementById("pqloadprogress").value = piratequesting.overlayRegistry.progress();
  				try {
  					sidebar.contentDocument.loadOverlay(nex.getOverlayFile(),this);
	  			} catch (error) {
  					cleanUp();
  					dump("Failed to load: " + nex.getOverlayFile() + "\nReported Error " + getErrorString(error));
	  			}
  			} else {
  				cleanUp();
	  		}
  		} catch (error) { alert(getErrorString(error)); }
  	}
  },
  register: function() {
    var observerService = Components.classes["@mozilla.org/observer-service;1"]
                          .getService(Components.interfaces.nsIObserverService);
    observerService.addObserver(this, "xul-overlay-merged", false);
  },
  unregister: function() {
    var observerService = Components.classes["@mozilla.org/observer-service;1"]
                            .getService(Components.interfaces.nsIObserverService);
    observerService.removeObserver(this, "xul-overlay-merged");
  }
}
</pre>
<p>And a stripped down version would look something like this: </p>
<pre>
function overlayObserver()
{
  this.register();
}
overlayObserver.prototype = {
  observe: function(subject, topic, data) {

  	if (topic == "xul-overlay-merged") {
		try {
			var nex = overlayRegistry.next();
			if (nex) {
  				try {
  					document.loadOverlay(nex.getOverlayFile(),this);
	  			} catch (error) {
  					dump("Failed to load: " + nex.getOverlayFile() + "\nReported Error " + getErrorString(error));
	  			}
  			} else {
  				cleanUp();
	  		}
  		} catch (error) { alert(getErrorString(error)); }
  	}
  },
  register: function() {
    var observerService = Components.classes["@mozilla.org/observer-service;1"]
                          .getService(Components.interfaces.nsIObserverService);
    observerService.addObserver(this, "xul-overlay-merged", false);
  },
  unregister: function() {
    var observerService = Components.classes["@mozilla.org/observer-service;1"]
                            .getService(Components.interfaces.nsIObserverService);
    observerService.removeObserver(this, "xul-overlay-merged");
  }
}
</pre>
<p>This observer chain is started with:</p>
<pre>
overlayObserver.observe(null,"xul-overlay-merged", null);
</pre>
<p>The observer code is also fairly simple but relies on some things that were not terribly well documented. The key thing to know about loadOverlay is that it raises an <code>xul-overlay-merged</code> observer notification. <a href="http://developer.mozilla.org>MDC</a> has a pretty good list of the observer notifications <a href="http://developer.mozilla.org/en/Observer_Notifications">here</a>, but you&#8217;ll notice what&#8217;s missing. <a href="https://developer.mozilla.org/en/Document.loadOverlay">This entry</a>, however, has that piece of info. If you&#8217;ve never used observers before, <a href="https://developer.mozilla.org/en/nsIObserver">this</a> gives a good rundown.</p>
<p>Sooo&#8230;. What happens? how does it work? Basically, at some point during the initialization of the sidebar (not important in this discussion), the observer chain is started and will loop as follows:</p>
<ol>
<li>receive notification of the last loadOverlay finishing</li>
<li>get the next item in the iterator</li>
<li>if the &#8220;next item&#8221; is null, stop</li>
<li>load the overlay file specified by said item</li>
</ol>
<p>And you&#8217;re done. One Note I would make is that if there are multiple extensions making use of this at the same time, you&#8217;re very likely to have problems when both extensions receive the notifications and both start loading their next items. As firefox still lacks a built-in queue for overlay loading, we&#8217;re stuck hoping that nobody else will use this at the same time.</p>
<p>Note: You may notice that a lot of the piratequesting code makes use of a function <code>getErrorString()</code>. This is a very siple function that puts all of the error info I want into a string. <code>dump()</code> is a function available in firefox for dumping text to the console. I am also currently working on an error logging system and will cover all of these issues in more detail when that is finished. For the time being, ignore how I handle the errors but for obvious reasons, you will want to have some kind of error handling in place.</p>
<p>Edit 2009/04/04:<br />
It has since occurred to me that by using additional information, that is, <code>subject</code>, from the observer notification, I can reduce the chances of conflict by ensuring it only fires on the completion of it&#8217;s own loadOverlay calls.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.ashita.org/the-loadoverlay-dilemma/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Functions in Closures</title>
		<link>http://www.ashita.org/functions-in-closures/</link>
		<comments>http://www.ashita.org/functions-in-closures/#comments</comments>
		<pubDate>Mon, 01 Dec 2008 07:47:25 +0000</pubDate>
		<dc:creator>Jonathan Fingland</dc:creator>
				<category><![CDATA[DOM]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[closures]]></category>

		<guid isPermaLink="false">http://ashita.org/?p=304</guid>
		<description><![CDATA[I last wrote about closures and how this affects the visibility of variables and functions. This time I&#8217;m going to introduce returning functions from a closure and how it can be useful in the first part. 
First off, lets say you have a strange need to create functions to consistently add a value like addFive, [...]]]></description>
			<content:encoded><![CDATA[<p>I last wrote about <a href="http://ashita.org/javascript-closures/">closures</a> and how this affects the visibility of variables and functions. This time I&#8217;m going to introduce returning functions from a closure and how it can be useful in the first part. </p>
<p>First off, lets say you have a strange need to create functions to consistently add a value like addFive, addTen, etc. Well this is one way to go about it.</p>
<pre>
function createAdder(addition_size) {
      return function (value) {
                     return value + addition_size;
               }
}

var addFive = createAdder(5);
var addTen = createAdder(10);

alert(addFive(3));
alert(addTen(-10));
</pre>
<p>The code above will alert 8 and 0. While this isn&#8217;t the most natural use of the technique, hopefully it is clear enough. <code>addition_size</code> is retained by the <code>addFive</code> and <code>addTen</code> functions because the function had visibility when it was declared. </p>
<p>One handy way to use this is when creating event handlers that need to take parameters. When adding a handler, you pass the function itself, which doesn&#8217;t provide an opportunity to add extra parameters, we can get around this by doing:</p>
<pre>
function getValuePlusFiveDisplayer(value) {
  return function (event) {
    var sum = addFive(value);
    alert(value + " + 5 = " + sum);
  }
}

var number_1 = document.getElementById("number_1");
number_1.addEventListener("click",getValuePlusFiveDisplayer(1),false);

var number_2 = document.getElementById("number_2");
number_2.addEventListener("click",getValuePlusFiveDisplayer(2),false);
</pre>
<p>And HTML like:</p>
<pre>
&lt;span id="number_1" class="number_button"&gt;1&lt;/span&gt;
&lt;span id="number_2" class="number_button"&gt;2&lt;/span&gt;
</pre>
<p>Which would work like this:</p>
<p><span id="number_1" style="margin:5px;display:inline-block;background-color:cornsilk; padding:3px;border:1px solid black;" >1</span><span id="number_2" style="display:inline-block; margin:5px;background-color:cornsilk;padding:3px;border:1px solid black;">2</span></p>
<p><script>
function createAdder(addition_size) {
      return function (value) {
                     return value + addition_size;
               }
}
var addFive = createAdder(5);
function getValuePlusFiveDisplayer(value) {
  return function (event) {
    var sum = addFive(value);
    alert(value + " + 5 = " + sum);
  }
}
var number_1 = document.getElementById("number_1");
number_1.addEventListener("click",getValuePlusFiveDisplayer(1),false);
var number_2 = document.getElementById("number_2");
number_2.addEventListener("click",getValuePlusFiveDisplayer(2),false);
</script></p>
<p>Even though you&#8217;re unlikely to need this exact example, hopefully it gives you some ideas, or helps solve some problems </p>
]]></content:encoded>
			<wfw:commentRss>http://www.ashita.org/functions-in-closures/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>JavaScript Closures</title>
		<link>http://www.ashita.org/javascript-closures/</link>
		<comments>http://www.ashita.org/javascript-closures/#comments</comments>
		<pubDate>Fri, 28 Nov 2008 01:26:10 +0000</pubDate>
		<dc:creator>Jonathan Fingland</dc:creator>
				<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://ashita.org/?p=287</guid>
		<description><![CDATA[Closures are one of the most powerful features of JavaScript. JavaScript isn&#8217;t the only language supporting this, but it&#8217;s certainly the one I&#8217;m going to discuss here. Just for example, the same thing can be done in ActionScript 3 &#8212; if you know how that works, you know how it works in JavaScript.
Getting down to [...]]]></description>
			<content:encoded><![CDATA[<p>Closures are one of the most powerful features of JavaScript. JavaScript isn&#8217;t the only language supporting this, but it&#8217;s certainly the one I&#8217;m going to discuss here. Just for example, the same thing can be done in ActionScript 3 &#8212; if you know how that works, you know how it works in JavaScript.</p>
<p>Getting down to the matter at hand, closures are essentially a way of managing variable scope. First lets look at some scope basics, though.</p>
<pre>
function User(name, age, address) {
     //name, age and address are all private to the scope of this function

     this.name = name;    // public property

     this.getAge = function () { return age; }; //public, privileged method

     function getAddress() { return address; }  //private method

}

User.prototype.getName = function () { return this.name; } //public, non-priveleged method

User.prototype.getAddress = function() { return address; } //fails. address is undefined in this scope.
</pre>
<p>Just to make it clear, you can have public properties and private variables, public &#8212; privileged and non-privileged &#8212; methods, and private methods. Privileged methods can access the variables and methods in the constructor (as well as the public ones), whereas non-priveleged methods can only access public members and methods.</p>
<p>Last week, I wrote this:</p>
<pre>
var myButton = document.getElementById("myButton");
myButton.addEventListener("click",
                               function (event) {
                                     alert("you clicked!");
                               },
                               false);
</pre>
<p>Now lets combine the two ideas:</p>
<pre>

function User(element, name, age, address) {
     //name, age and address are all private to the scope of this function

     this.name = name;    // public property

     this.getAge = function () { return age; }; //public, privileged method

     function getAddress() { return address; }  //private method

     element.addEventListener("click", function (event) { alert(this.name + "\n" + age + "\n" + getAddress()); }, false);

}
var myButton = document.getElementById("myButton");
var jon = new User(myButton, "Jon", 98, "123 fourth street, yourtown");
</pre>
<p>Now, if I click on <code>myButton</code> I&#8217;ll get an alert with all of the information&#8230;. except name. When the event handler executes, the value of <code>this</code> has changed. The easiest way to get around this is by taking advantage of closures and <em>not</em> use <code>this</code> by using <code>var self = this;</code></p>
<pre>

function User(element, name, age, address) {
     //name, age and address are all private to the scope of this function

     this.name = name;    // public property

     this.getAge = function () { return age; }; //public, privileged method

     function getAddress() { return address; }  //private method
     var self = this;
     element.addEventListener("click", function (event) { alert(self.name + "\n" + age + "\n" + getAddress()); }, false);

}
var myButton = document.getElementById("myButton");
var jon = new User(myButton, "Jon", 98, "123 fourth street, yourtown");
</pre>
<p>Now it works. it&#8217;s a very small change and it means that by taking advantage of closures we can maintain a reference to this even when the context changes. This technique is extremely common in event handlers, but it&#8217;s also very useful when using <code>setTimeout</code> or <code>setInterval</code> (which use <code>window</code> as context)</p>
<p>Another use of this is to wrap functions that can see internal data. I&#8217;ll explain that more in the next post.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.ashita.org/javascript-closures/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
