<?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>SwiftLizard Interactive {Design, Development} &#187; javascript</title>
	<atom:link href="http://www.swift-lizard.com/category/javascript/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.swift-lizard.com</link>
	<description>all about a it - freelancers life</description>
	<lastBuildDate>Thu, 18 Mar 2010 09:10:34 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Javascript leashed with google Caja</title>
		<link>http://www.swift-lizard.com/2009/12/19/javascript-leashed-with-google-caja/#utm_source=feed&amp;utm_medium=feed&amp;utm_campaign=feed</link>
		<comments>http://www.swift-lizard.com/2009/12/19/javascript-leashed-with-google-caja/#comments</comments>
		<pubDate>Sat, 19 Dec 2009 00:16:50 +0000</pubDate>
		<dc:creator>Chris</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[caja]]></category>
		<category><![CDATA[security]]></category>

		<guid isPermaLink="false">http://www.swift-lizard.com/?p=230</guid>
		<description><![CDATA[Like I wrote recently I am contracted at a German ISP at the moment to build a new Portal where one can put several different widgets on his or her personal web page. Similar to igoogle. My customer also wants to provide the possibility of own widgets to external developers, so to avoid security issues [...]]]></description>
			<content:encoded><![CDATA[<p>Like I wrote recently I am contracted at a German ISP at the moment to build a new Portal where one can put several different widgets on his or her personal web page. Similar to igoogle. My customer also wants to provide the possibility of own widgets to external developers, so to avoid security issues we will need to sandbox each of those widgets, but like we all know that can be a serious problem when it comes to the &#8220;evil unleashed monster&#8221; javascript. So in order to leash it inside a sandbox on a secure chain we came across <a title="Google Caja project page" href="http://code.google.com/p/google-caja/" target="_blank">google caja</a>.<span id="more-230"></span></p>
<p>Caja is a project started by google a few years ago to provide a way to safely embed third party DHTML code on your own web page, as well as rich communication interfaces between the embedding page and the embedded applications. Normally to embed third party code one would use iframes, but with the capability of javascript to communicate between frames this can be a serious security breach.</p>
<p>At this point google caja provides you with a neat solution. First of all you will not need any iframes to embed third party code on your web page safely, the java based cajoler will provide you with html and javascript that is sand-boxed and secure to embed once it is cajoled. Don&#8217;t get me wrong, Java will only be needed to compile possibly hazardous code once, into the cajoled secure  code one can use on his website. After that it is all done by the javascript libraries provided by the caja project.</p>
<p>But let me show you how the magic works.</p>
<p>First of all you will need to install some software:</p>
<ul>
<li><a rel="nofollow" href="http://java.sun.com/javase/downloads/index.jsp">JDK</a> 6</li>
<li>The <a rel="nofollow" href="http://subversion.tigris.org/project_packages.html">subversion</a> version manager</li>
<li>The <a rel="nofollow" href="http://ant.apache.org/manual/install.html">Apache Ant</a> build system.</li>
<li>The <a rel="nofollow" href="http://sourceforge.net/project/showfiles.php?group_id=15278&amp;package_id=12472">JUnit</a> testing framework.  Just drop junit.jar&lt;/tt&gt; in the $ANT_HOME/lib directory you set up for Ant.</li>
</ul>
<p>Then create some folders for your caja project, for this I assume you will use Linux or Mac OS:</p>
<pre name="code" class="java">

mkdir caja
cd caja
mkdir svn-changes
cd svn-changes
mkdir pristine
cd pristine
</pre>
<p>After you have done this you will need to check out caja from the SVN &#8211; Repository:</p>
<pre name="code" class="java">svn checkout http://google-caja.googlecode.com/svn/trunk/ google-caj</pre>
<p>Following the wiki of the caja project I assumed simply running &#8220;ant demos&#8221; on the console would provide me with some working demos. To make a long story of yelling and cursing short, no it didn`t. After long sessions of trail and error and a post on the discussion board where Jasvir Nagra pointed me in the right direction I found out why.</p>
<p>First of all several sources of the projects wiki as well as the sources compiled by ant will show you that you have to integrate the valija js the following way:</p>
<pre name="code" class="html">&lt;script src="valija.co.js" type="text/javascript"&gt;&lt;/script&gt;</pre>
<p>;<br />
What´s the problem with that ? There is simply no valija.co.js anywhere in the whole project !! But there is a &#8220;valija.out.js&#8221;. Simply use that file name and one of your setup problems will be gone. Yes right, one, there are several more traps I will show you.</p>
<p>Next thing you will notice, running firebug, is that cajoling source ,either via applet or via war (generated via ant playground), will not work but return a 500 Internal Server error.</p>
<p>Though I am a huge fan of software running out of the box I assumed that running either &#8220;ant playground&#8221; or &#8220;ant demos&#8221; ( / &#8220;ant testbed&#8221; for testbed only) would provide me with a running demo to play with. It didn´t. The reason why I found out after I had setup jetty Java server in debug mode, like Jasvir suggested. The log then showed me that some nu.validator.* library was missing in my jar file that was compiled by ant. Because I had been looking through all the project files and folders at my days of yelling and cursing I new where to find it. This Lib with all the needed classes is stored in &#8220;$cajaSourceFolder/third-party/java/htmlparser/src&#8221;. So there is a simply solution for that, simply copy the &#8220;nu&#8221; &#8211; folder to &#8220;$cajaSourceFolder/src&#8221; and run &#8220;ant testbed&#8221; or &#8220;ant playground&#8221; again.</p>
<p>Tada,&#8230; problem solved. Either you will get a working testbed by now or a working playground war.</p>
<p>To play at the playground I would suggest that you use jetty. The use of the server to my mind is quite easy. Simply download the src <a href="http://dist.codehaus.org/jetty/jetty-hightide-7.0.1/" target="_blank">here</a>, unpack it, switch to the folder and run:</p>
<pre name="code" class="java">
$cajaSourceFolder: ant playground
$jettyHomeDir/webapps:ln -s $cajaHomeDir/ant-war caja-playground
cd ..
$jettyHomeDir: java -jar start.jar etc/jetty-logging.xml etc/jetty.xml
</pre>
<p>By now you will have jetty running on port 8080 at localhost and caja-playground can be found at:</p>
<p>http://localhost:8080/caja-playground</p>
<p>But we don´t only want to play do we ? <img src='http://www.swift-lizard.com/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </p>
<p>So after playing around a little bit with either the playground or the testbed application I assume you would like to use what you have produced with either of those in a simple host page. Ten years of doing this job by now I thought the wiki might provide me with a simple solution for a host page that would be working right away. Hhmmm sorry nope. Wrong again. It does not.</p>
<p>Don`t get me wrong there is an example. It simply does not work with the code that you can download at the projects page. Simple as that. But this could not keep me from setting up one simple example, by braking down the playgrounds web page to the minimum needed to get it running.</p>
<p>Same procedure as every year Ms Sofia ? Same procedure as every year James. If nothing helps reverse engineering does it each and every time.</p>
<p>The nice guy I am I will save you some time and give you a step by step of what is needed to get the cajoled code running in a simple as can be host page.</p>
<p>First thing you will need to get the cajoled code running will be this inside the body tag of your page:</p>
<pre name="code" class="html">
&lt;!-- Load all needed scripts --&gt;
     &lt;script src="cajita.js" type="text/javascript"&gt;&lt;/script&gt;
     &lt;script src="unicode.js" type="text/javascript"&gt;&lt;/script&gt;
     &lt;script src="css-defs.js" type="text/javascript"&gt;&lt;/script&gt;
     &lt;script src="html4-defs.js" type="text/javascript"&gt;&lt;/script&gt;
     &lt;script src="html-sanitizer.js" type="text/javascript"&gt;&lt;/script&gt;
     &lt;script src="html-emitter.js" type="text/javascript"&gt;&lt;/script&gt;
     &lt;script src="setup-valija.js" type="text/javascript"&gt;&lt;/script&gt;
     &lt;script src="bridal.js" type="text/javascript"&gt;&lt;/script&gt;
     &lt;script src="domita.js" type="text/javascript"&gt;&lt;/script&gt;
     &lt;script src="valija.out.js" type="text/javascript"&gt;&lt;/script&gt;
</pre>
<p>The next step will be to provide a method that will assign the containers for your cajoled widget:</p>
<pre name="code" class="html">
&lt;script type="text/javascript"&gt;
  var imports = ___.copy(___.sharedImports);
  var gadgetRoot = "";
  imports.outers = imports;

  function setGadgetContainer(containerId){
    gadgetRoot = document.getElementById(containerId);
    imports.htmlEmitter___ = new HtmlEmitter(gadgetRoot);
    attachDocumentStub('-g___', {
      rewrite: function(){
        return null;
      }
    }, imports, gadgetRoot);
    imports.$v = valijaMaker.CALL___(imports.outers);
    ___.getNewModuleHandler().setImports(imports);
  }
&lt;/script&gt;
</pre>
<p>This code simply initiates the base for caja and assigns a container for the widget. But lets go on with the html you will need for your page:</p>
<pre name="code" class="html">
&lt;div id="cajoled-output" class="g___"&gt;
           {Here goes the html output of the cajoler}&lt;/div&gt;

&lt;!-- Load widget 1 --&gt;
&lt;script type="text/javascript"&gt;setGadgetContainer("cajoled-output");&lt;/script&gt;
&lt;!-- The Cajoled javascript output put in an external file --&gt;
&lt;script src="widgets/widget1.vo.js" type="text/javascript"&gt;&lt;/script&gt;
</pre>
<p>You might have recognized the &#8221; class=&#8217;g___&#8217; &#8221; that is also mentioned in the js method. This is nescessary for the html code rendered dynamicly by the caja libary to assign the content to the container.</p>
<p>This is it. If you followed the instructions you should have a working google caja playground, demo, webservice and jetty server by now as well as a working basic stand alone page witch will run you cajoled code.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.swift-lizard.com/2009/12/19/javascript-leashed-with-google-caja/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Development with jQuery &amp; Qunit</title>
		<link>http://www.swift-lizard.com/2009/11/24/test-driven-development-with-jquery-qunit/#utm_source=feed&amp;utm_medium=feed&amp;utm_campaign=feed</link>
		<comments>http://www.swift-lizard.com/2009/11/24/test-driven-development-with-jquery-qunit/#comments</comments>
		<pubDate>Tue, 24 Nov 2009 01:13:30 +0000</pubDate>
		<dc:creator>Chris</dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[agile development]]></category>
		<category><![CDATA[continuous integration]]></category>
		<category><![CDATA[qunit]]></category>

		<guid isPermaLink="false">http://www.swift-lizard.com/?p=172</guid>
		<description><![CDATA[Though a friend of mine and myself lately started again with continuous integration projects for the company&#8217;s we work for, and we both like test driven development, if it is no overkill, I came across Qunit which is a library provided by jQuery for Unittesting javascript. Until last week I did not even know something [...]]]></description>
			<content:encoded><![CDATA[<p>Though a friend of mine and myself lately started again with continuous integration projects for the company&#8217;s we work for, and we both like test driven development, if it is no overkill, I came across Qunit which is a library provided by jQuery for Unittesting javascript. Until last week I did not even know something like this existed for Javascript, but I am very happy that I came across this .  Because I think unittests are a good way to assure that your code works as expected, I´d like to show you how to setup and write jQuery unittests.<span id="more-172"></span></p>
<p>First of all you will need to download the following two files from the jQuery Api &#8211; Docs Website:</p>
<p><a href="http://github.com/jquery/qunit/raw/master/qunit/qunit.js" target="_blank">Qunit.js</a><br />
<a href="http://github.com/jquery/qunit/raw/master/qunit/qunit.css" target="_blank">Qunit.css</a></p>
<p>Afterwards you will need to create a new html file with the following code:</p>
<pre name="code" class="html">&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
      "http://www.w3.org/TR/html4/loose.dtd"&gt;
&lt;html&gt;
  &lt;head&gt;
    &lt;link rel="stylesheet" href="core/qunit.css" type="text/css"/&gt;
    &lt;script src="http://code.jquery.com/jquery-latest.js"&gt; &lt;/script&gt;
    &lt;script type="text/javascript" src="core/qunit.js"&gt;&lt;/script&gt;
    &lt;script type="text/javascript"&gt;
     // --- Unittest Code goes here ---
    &lt;/script&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;h1 id="qunit-header"&gt;QUnit example&lt;/h1&gt;
    &lt;h2 id="qunit-banner"&gt;&lt;/h2&gt;
    &lt;h2 id="qunit-userAgent"&gt;&lt;/h2&gt;
    &lt;ol id="qunit-tests"&gt;
    &lt;/ol&gt;
  &lt;/body&gt;
&lt;/html&gt;</pre>
<p>This Html file will be the page we can view the testresults on.</p>
<p>In this tutorial I only like to give you a brief overview  of what can be done how, because most of you will be familiar with writing unittests at other languages, and in the case of javascript and jQuery this will be almost the same.</p>
<p>So lets go write our first unittest:</p>
<pre name="code" class="javascript">  $(document).ready(function(){
    module("Basic Unit Test");
    test("Sample test", function()
    {
       expect(1);
       equals(divide(4,2),
        2,
        'Expected 2 as the result, result was: ' + divide(4,2));
    });
  });</pre>
<p>If you now open the the html page in your prefered browser you will see something like this:</p>
<p><a href="http://www.swift-lizard.com/wp-content/uploads/2009/11/Bildschirmfoto-2009-11-24-um-00.40.58.png#utm_source=feed&amp;utm_medium=feed&amp;utm_campaign=feed" rel="shadowbox"><img class="alignnone size-medium wp-image-193" title="Qunit first test" src="http://www.swift-lizard.com/wp-content/uploads/2009/11/Bildschirmfoto-2009-11-24-um-00.40.58-300x108.png" alt="Qunit first test" width="300" height="108" /></a></p>
<p>Your unittest failes, just like one might have expected because we never implemented the divide method into our code. But lets go step by step. You might have recognized several different parts of code in the js &#8211; snippet that need a little explanation.</p>
<p>First of all we have a line &#8220;module(&#8220;Basic Unit Test&#8221;);&#8221;. By adding this we are able to separate the modules we want to test visually on the test page. If you take a look on that page after running the tests you will read &#8220;<strong>1. Basic Unit Test module</strong>: Sample test (1, 0, 1)&#8221; at the moment. So the string we have set by adding &#8220;module(&#8220;Basic Unit Test&#8221;);&#8221; to our code is displayed there as well as some more information we have provided by the lines that followed this one.</p>
<p>Next line we have added so far was &#8220;test(&#8220;Sample test&#8221;, function(){});&#8221;. This is basically the declaration of a single test that you run. The first parameter is a String that simply gives the test a name(&#8220;1. Basic Unit Test module:<strong> Sample test</strong> (1, 0, 1)&#8221;), the second one is a callback function that is called the moment we run the test by loading the page.  Lets go on analyzing the code we just tested.</p>
<p>Next thing you might have recognized is &#8220;expect(1);&#8221;, this is a simple declaration how many assertions we expect at this single test. At the moment we run only one so this is set to one. If we had set this one to two for instance, the result of our test would be that not one assertion has failed but two, because in that case we would also have forgotten to implement the second assertion.</p>
<p>Lets move on to the last line we just implemented &#8220;equals(divide(4,2),2,&#8217;Expected 2 as the result, result was: &#8216; + divide(4,2));&#8221;.  This is the actual assertion we wanted to make, just to make sure that the method &#8220;divide&#8221; works properly and returns the mathematical correct result. The Qunit method equals takes three parameters. The first one and the second one are the ones compared, the third is a String, a message you might want to print out. This message is handled by the Qunit.log() method I will show you later.</p>
<p>Besides the method equals there are two more methods provided to you for testing. They are called &#8220;ok&#8221; and &#8220;same&#8221;. While &#8220;ok&#8221; is a simple Boolean check and for this only takes two parameters, the Boolean value that has to be true in order to not make the test fail, and a message, the &#8220;same&#8221; method is kind of like equal. The only difference between those two is that equal only returns true if both, the first and the second parameter, are 100% equal ( like a === b), and same only compares the variables values vs. each other.</p>
<p>But let me give you some example code:</p>
<pre name="code" class="javascript">  var arrayContainer = {a: 'firstElement'};
  equals(arrayContainer, {a: 'firstElement'}, 'Will fail');
  same(arrayContainer, {a: 'firstElement'}, 'Will pass');</pre>
<p>After describing the basics to you we can now start to make our test working. This is quite easy just add the following to your code:</p>
<pre name="code" class="javascript">  function divide(a,b)
  {
    return a / b;
  }</pre>
<p><a href="http://www.swift-lizard.com/wp-content/uploads/2009/11/Bildschirmfoto-2009-11-24-um-01.24.46.png#utm_source=feed&amp;utm_medium=feed&amp;utm_campaign=feed" rel="shadowbox"><img class="alignnone size-medium wp-image-202" title="Qunit test pass" src="http://www.swift-lizard.com/wp-content/uploads/2009/11/Bildschirmfoto-2009-11-24-um-01.24.46-300x115.png" alt="Qunit test pass" width="300" height="115" /></a></p>
<p>Your unit test passed, congratulations. But if you are a little bit like me you are missing the message we added to the equals assertion in our test, it is not displayed anywhere at our page, and even if you look at the console there will be nothing. This is because the public method Qunit.log() was indeed declared in the class file, but no code that would display the messages has been implemented. To my mind this was because the developers of Qunit wanted it to be up to your decision whether or not you like to display them.</p>
<p>It is done really easy and in this tutorial I will show you how to display them in the console of the browser (though it has one), just add the following on top of the ready callback :</p>
<pre name="code" class="javascript">  QUnit.log = function(result, message)
  {
    if (window.console &amp;&amp; window.console.log)
    {
      window.console.log(result +' :: '+ message);
    }
  }</pre>
<p>If you now reload the Unittest page,  open up Firebug for instance (in prior), and switch to the console view of Firebug you will see this:</p>
<p><a href="http://www.swift-lizard.com/wp-content/uploads/2009/11/Bildschirmfoto-2009-11-24-um-01.38.33.png#utm_source=feed&amp;utm_medium=feed&amp;utm_campaign=feed" rel="shadowbox"><img class="alignnone size-medium wp-image-205" title="Qunit Test with Firebug" src="http://www.swift-lizard.com/wp-content/uploads/2009/11/Bildschirmfoto-2009-11-24-um-01.38.33-300x150.png" alt="Qunit Test with Firebug" width="300" height="150" /></a></p>
<p>By now you should have the gear to develop some unittest for jQuery or any other javascript  you use might in your project. I hope this tutorial has given you a good overview and a nice point to start from. </p>
<p>The following link provides a zip file with the summary of this tutorial:<br />
<a href='http://www.swift-lizard.com/wp-content/uploads/2009/11/jQunit.zip'>jQunit-tutorial.zip</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.swift-lizard.com/2009/11/24/test-driven-development-with-jquery-qunit/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>jQuery sortable with Iframes in FireFox</title>
		<link>http://www.swift-lizard.com/2009/11/15/jquery-sortable-with-iframes-in-firefox/#utm_source=feed&amp;utm_medium=feed&amp;utm_campaign=feed</link>
		<comments>http://www.swift-lizard.com/2009/11/15/jquery-sortable-with-iframes-in-firefox/#comments</comments>
		<pubDate>Sun, 15 Nov 2009 22:33:32 +0000</pubDate>
		<dc:creator>Chris</dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[jquery]]></category>

		<guid isPermaLink="false">http://swift-lizard.com/?p=98</guid>
		<description><![CDATA[I came across this problem a week ago when I tried to develop an interface between an Iframe, or in Detail it&#8217;s content, and the iframes parent page. Turns out that the following code wouldn´t work in FireFox although all other browsers, yes even our friend the Internet Explorer, would behave as expected.
   [...]]]></description>
			<content:encoded><![CDATA[<p>I came across this problem a week ago when I tried to develop an interface between an Iframe, or in Detail it&#8217;s content, and the iframes parent page. Turns out that the following code wouldn´t work in FireFox although all other browsers, yes even our friend the Internet Explorer, would behave as expected.<span id="more-98"></span></p>
<pre name="code" class="javascript">   function accessIframeJS(IframeName, methodName, methodParams)
   {
    var  IFrameObj  = window.frames[IframeName];
    var  methodCall = "IFrameObj."+methodName+"("+ methodParams +")";

    try{
       eval(methodCall);
    }catch(error){
       // some code here for error handling
    }
   }</pre>
<p>Traced on Firebug it turns out that FireFox loses the IFrameObj on Drag &amp; Drop while rewriting the DOM. Took me quite a while, and a long talk with uncle google until I took a look at bugzilla of mozzilla and the huge amount of iframe Bugs mentioned there. But I found the solution after reading alot of those posts,.. and yes as all ways it is an easy one, if you knew the solution.</p>
<pre name="code" class="javascript">function accessIframeJS(iframeId, methodName, methodParams)
 {
  var IFrameObj = document.getElementById(iframeId).contentWindow;
  var methodCall = "IFrameObj."+methodName+"("+ methodParams +")";

  try{
     eval(methodCall);
  }catch(error){
     // some code here for error handling
  }
 }</pre>
<p>Ta ta,&#8230; this works everywhere,&#8230; but it took me a long search, until I found the post in Bugzilla.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.swift-lizard.com/2009/11/15/jquery-sortable-with-iframes-in-firefox/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>How to develop a jQuery plugin</title>
		<link>http://www.swift-lizard.com/2009/11/15/how-to-develop-a-jquery-plugin/#utm_source=feed&amp;utm_medium=feed&amp;utm_campaign=feed</link>
		<comments>http://www.swift-lizard.com/2009/11/15/how-to-develop-a-jquery-plugin/#comments</comments>
		<pubDate>Sun, 15 Nov 2009 14:15:47 +0000</pubDate>
		<dc:creator>Chris</dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[jquery]]></category>

		<guid isPermaLink="false">http://swift-lizard.com/?p=51</guid>
		<description><![CDATA[Lately I started a new project at a German ISP where we (the team and me) have to develop several extensions to jQuery in order to build a framework to work with in this project. I am using jQuery for several years now but never had to develop my own extensions, because most of the [...]]]></description>
			<content:encoded><![CDATA[<p>Lately I started a new project at a German ISP where we (the team and me) have to develop several extensions to jQuery in order to build a framework to work with in this project. I am using jQuery for several years now but never had to develop my own extensions, because most of the plugins available solved problems I came a cross. This time I have to do my own and started questioning uncle google about how to do it. No surprise there are several approaches to do a plugin for jQuery, but none of the tutorials I found answered all my Questions completely, so I decided to write this sum up of what I learned.</p>
<p><span id="more-51"></span></p>
<p>First of all you will need the basic wrapping:</p>
<pre name="code"  class="javascript">(function($){
   // your js code goes here
})(jQuery);</pre>
<p>This wrapping adds your code to the jQuery library if you add the js file to your page.<br />
Next thing you will have to do is add the basic functionality to your plugin.</p>
<pre name="code"  class="javascript">$.fn.yourPlugin = function(options){
}</pre>
<p>By adding those lines to your js file within the first code snippet you now can access your plugin by:</p>
<pre class="javascript">$('#yourDomElement').yourPlugin();</pre>
<p>Next you need to know the difference between private and public vars within the class you are developing. If you write something like:</p>
<pre name="code" class="javascript">   /**
     * default options for plugin
     * private
     * @var array defaultOptions
     */
    var defaultOptions = {
        action:       false,
        debug:        false
    }</pre>
<p>This would be a private var witch is only accessible within the class it self. If you need to have a var of your class to be public you have to write something like this:</p>
<pre name="code" class="javascript">   /**
     * default options for plugin
     * public
     * @var array defaultOptions
     */
    $.fn.yourPlugin.defaultOptions = {
        action:       false,
        debug:        false
    }</pre>
<p>One word has to be said by now, public variables can only be defined after the declaration of the constructor of your plugin, otherwise the compiler will throw a nice little javascript error because &#8220;yourPlugin&#8221; was not defined yet.<br />
Now that we have learned this we can go on with the possibility of configuration for the plugin. Like in every other language we will need to have some basic properties for the class that can be overwritten by your needs. To do something like that is quite simple:</p>
<pre name="code" class="javascript">   /**
     * yourPlugin base constructor
     *
     * @param [] options
     * @return void
     */
    $.fn.yourPlugin = function(options){
        // extend default options with overrides
        var opts = $.extend({}, defaultOptions, options);
    }</pre>
<p>So by now you can set the options you need by writing something like this:</p>
<pre name="code" class="javascript">   $('#yourDomElement').yourPlugin({
      action:       myAction
    });</pre>
<p>In this case you would have set opts.action from &#8220;false&#8221; to &#8220;myAction&#8221;.<br />
Next  we will go to private and public class methods. It is allmost the same as defining public and private member variables of your class.<br />
Something like this would be private:</p>
<pre name="code" class="javascript">   /**
     * private
     * method to do some vodoo
     */
    function yourPrivateClassMethod()
    {
        // the methods code
    }</pre>
<p>And something like this is a public method:</p>
<pre name="code" class="javascript">   /**
     * public
     * method to do some vodoo
     */
    $.fn.yourPlugin.yourPublicClassMethod = function()
    {
        // the methods code
    }</pre>
<p>Same rules like for the public member variables,&#8230; they have to be declared after your constructor, otherwise you will get an error. Another word of advise,.. as a developer I thought to access variables and methods within a class I can go by &#8220;this&#8221;,.. forget &#8220;this&#8221;,.. private methods and vars are accessed directly by their name, the public one you can access either by $(this).yourPlugin.yourPublicClassMethod() or $.fn.yourPlugin.yourPublicClassMethod().</p>
<p>So by now, if we put together the things we learned, we can do something like this:</p>
<pre name="code" class="javascript">(function($){
   /**
     * default options for plugin
     * private
     * @var array defaultOptions
     */
    var defaultOptions = {
        action:       false,
        debug:        false
    }

    /**
     * yourPlugin base constructor
     *
     * @param [] options
     * @return void
     */
    $.fn.yourPlugin = function(options){
        // extend default options with overrides
        var opts = $.extend({}, defaultOptions, options);

        switch(opts.action)
        {
        	case 'private':
        		yourPrivateClassMethod();
        		break;

        	case 'public':
        		$.fn.yourPlugin.yourPublicClassMethod();
        		break;
        }
    }

    /**
     * public
     * method to do some vodoo
     */
    $.fn.yourPlugin.yourPublicClassMethod = function()
    {
    	// should alert 'false', 'false',
    	//because the public vars where not set

        alert($.fn.yourPlugin.defaultOptions.action);
        alert($.fn.yourPlugin.defaultOptions.debug);
    }

    /**
     * default options for plugin
     * public
     * @var array defaultOptions
     */
    $.fn.yourPlugin.defaultOptions = {
        action:       false,
        debug:        false
    }

    /**
     * private
     * method to do some vodoo
     */
    function yourPrivateClassMethod()
    {
        alert('This method is private');
    }

})(jQuery);</pre>
<p>I hope this little summary helped a little in understanding how javascript classes and jQuery work.<br />
If you have any suggestion or did see some errors in this tutorial please let me know about it.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.swift-lizard.com/2009/11/15/how-to-develop-a-jquery-plugin/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

