<?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>muhuk.com &#187; object oriented</title>
	<atom:link href="http://www.muhuk.com/tag/object-oriented/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.muhuk.com</link>
	<description>know thyself</description>
	<lastBuildDate>Wed, 07 Jul 2010 10:26:39 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Django Permission System</title>
		<link>http://www.muhuk.com/2009/05/django-permission-system/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=django-permission-system</link>
		<comments>http://www.muhuk.com/2009/05/django-permission-system/#comments</comments>
		<pubDate>Thu, 14 May 2009 13:40:22 +0000</pubDate>
		<dc:creator>Atamert Ölçgen</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[authentication]]></category>
		<category><![CDATA[django]]></category>
		<category><![CDATA[object oriented]]></category>

		<guid isPermaLink="false">http://www.muhuk.com/?p=210</guid>
		<description><![CDATA[Permission system that comes with django.contrib.auth allows you to create and assign permissions for your models. Permissions can be assigned to users or groups. A user has permissions directly assigned to her as well as permissions inherited from her groups. Permission scope is always model classess (as opposed to individual model instances). That means if [...]]]></description>
			<content:encoded><![CDATA[<p>Permission system that comes with <code>django.contrib.auth</code> allows you to create and assign permissions for your models. <a href="http://docs.djangoproject.com/en/dev/topics/auth/#permissions">Permissions</a> can be assigned to <a href="http://docs.djangoproject.com/en/dev/topics/auth/#users">users</a> or <a href="http://docs.djangoproject.com/en/dev/topics/auth/#groups">groups</a>. A user has permissions directly assigned to her as well as permissions inherited from her groups. Permission scope is always model classess (as opposed to individual model instances). That means if you are just checking <code>FooModel</code>.<code>can_do_bar</code> permission on a user; that user can <code>do bar</code> on all <code>FooModel</code> instances.</p>

<p>This built-in permission system is simple; as in you shouldn&#8217;t expect complex authorization schemes to be implemented easily. It is mainly used by <code>django.contrib.admin</code> and you can use it without any hassle for your very simple authorization requirements. Beauty of this permission system is it&#8217;s simplicity. Here are a few strong points:</p>

<ul>
<li>All your models get <strong>add</strong>, <strong>change</strong> and <strong>delete</strong> permissions created automatically.<sup>1</sup> These three are all you need for most of your models.</li>
<li><code>Admin</code> uses permissions internally. But more importantly permissions can be granted/revoked dynamically via admin.</li>
<li>Simple design encourages you to keep authorization scheme clean.<sup>2</sup></li>
</ul>

<p>The last point is very important; permissions shouldn&#8217;t leak into business logic. If you have a project that goes beyond a CMS, you probably have <em>business objects</em>. Business objects might have quite complex states and typically interact with each other in more than straightforward ways. On the other hand models in CMS style projects have simple states that are independent (of other models). Take a blog post; it is either published or not and its author is simply a <code>ForeignKey</code> to <code>User</code>s. If you depend heavily upon permissions for complex state transitions of your models you will soon find yourself in a dead end.</p>

<h3>Permissions in Fixtures</h3>

<p>One problem, and it&#8217;s a big problem, I&#8217;ve had with permissions is that; <strong>you can&#8217;t store permissions in <a href="http://docs.djangoproject.com/en/dev/topics/serialization/">fixtures</a></strong>. Here is what happens:</p>

<ol>
<li>Relationships are stored in fixtures as primary keys.</li>
<li>Permission are created by the framework programmatically in a specific order.</li>
<li>When you add/delete a new model or add/delete a custom permission this order changes.</li>
<li>Therefore primary keys of permissions change.</li>
<li>As a result permission data in your fixture are invalid.</li>
</ol>

<p>I&#8217;m a big fan of fixtures. More often than not you have some models that will be used as definitions (they&#8217;re partially fixed data) or you want to kickstart your project with placeholder data. It&#8217;s quite easy in Django. After creating your models, launch admin and create your data. Then simply <code>dumpdata</code>, maybe post-process a little bit and you have your <code>initial_data</code>! Not so easy if you have permissions in that basket.</p>

<p>Best solution I can come up with now is to <a href="http://docs.djangoproject.com/en/dev/topics/signals/#listening-to-signals">hook a <code>post_syncdb</code> function</a> and add your permissions programmatically.</p>

<h3>Authorization</h3>

<p>Basic usage of permissions is to check if a user has a certain <code>Permission</code> and branch accordingly:</p>

<pre>@login_required
def some_view(request):
    user = request.user
    <b>if user.has_perm('foo.bar_baz'):
        <i># go on and bar that baz</i>
    else:
        <i># display an error message</i></b>
    # ...rest of the view
</pre>

<p>When you need to combine conditions, it is a good idea to abstract authorization check in a function:</p>

<pre>class Foo(models.Model):
    # stuff that goes into a model

    <b>def can_bar(self, user):
        return user.has_perm('app.bar_foo') and user.baz >= self.baz</b></pre>

<p>You can combine this with techniques explained in <a href="http://www.b-list.org/weblog/2008/nov/09/dynamic-forms/">here</a> and <a href="http://www.b-list.org/weblog/2008/dec/24/admin/">here</a> to achieve column level permissions.</p>

<p>Row level permissions are cooking as well. There is a branch for <a href="http://code.djangoproject.com/wiki/RowLevelPermissions">per object permissions</a>. You can checkout this branch from subversion with the following command:</p>

<pre><code>svn co http://code.djangoproject.com/svn/django/branches/per-object-permissions
</code></pre>

<h3>Generic Permissions</h3>

<p>Let&#8217;s define permissions problem in a more generic way. A permission determines if:</p>

<ul>
<li>An <strong>actor</strong> can</li>
<li>Perform an <strong>action</strong></li>
<li>On an <strong>object</strong></li>
<li>Depending on arbitrary number of runtime <strong>conditions</strong> [optional]</li>
</ul>

<p>In our little implementation actors will be <code>auth.User</code> instances and objects, naturally, models. Actions will simply be keys of string type. Because of the possibility that our permission can have conditions, it should be a callable. Then we will have all the power Python/Django has.</p>

<p>Let&#8217;s place our permissions on our models:</p>

<pre><span style="color:#555555">   1 </span><span style="color:#000000; font-weight:bold">class</span> <span style="color:#010181">FooPermissions</span><span style="color:#000000">(</span>PermissionMixin<span style="color:#000000">):</span>
<span style="color:#555555">   2 </span>    <span style="color:#000000; font-weight:bold">def</span> <span style="color:#010181">__warg</span><span style="color:#000000">(</span>self<span style="color:#000000">):</span>
<span style="color:#555555">   3 </span>        <span style="color:#000000; font-weight:bold">return</span> <span style="color:#830000">max</span><span style="color:#000000">(</span>self<span style="color:#000000">.</span>quux <span style="color:#000000">-</span> self<span style="color:#000000">.</span>parent<span style="color:#000000">.</span>quux<span style="color:#000000">,</span> <span style="color:#2928ff">1</span><span style="color:#000000">)</span>
<span style="color:#555555">   4 </span>
<span style="color:#555555">   5 </span>    <span style="color:#000000">&#64;</span><span style="color:#830000">staticmethod</span>
<span style="color:#555555">   6 </span>    <span style="color:#000000; font-weight:bold">def</span> <span style="color:#010181">allows_bar_for</span><span style="color:#000000">(</span>actor<span style="color:#000000">):</span>
<span style="color:#555555">   7 </span>        <span style="color:#000000; font-weight:bold">return</span> actor<span style="color:#000000">.</span><span style="color:#010181">has_perm</span><span style="color:#000000">(</span><span style="color:#ff0000">'app.bar_foo'</span><span style="color:#000000">)</span> <span style="color:#000000; font-weight:bold">and</span> actor<span style="color:#000000">.</span>status <span style="color:#000000">==</span> <span style="color:#ff0000">'barrable'</span>
<span style="color:#555555">   8 </span>
<span style="color:#555555">   9 </span>    <span style="color:#000000; font-weight:bold">def</span> <span style="color:#010181">allows_baz_for</span><span style="color:#000000">(</span>self<span style="color:#000000">,</span> actor<span style="color:#000000">):</span>
<span style="color:#555555">  10 </span>        <span style="color:#000000; font-weight:bold">if</span> self<span style="color:#000000">.</span>qux_set<span style="color:#000000">.</span><span style="color:#010181">count</span><span style="color:#000000">() &gt;</span> <span style="color:#2928ff">10</span><span style="color:#000000">:</span>
<span style="color:#555555">  11 </span>            <span style="color:#000000; font-weight:bold">return True</span>
<span style="color:#555555">  12 </span>        <span style="color:#000000; font-weight:bold">else</span><span style="color:#000000">:</span>
<span style="color:#555555">  13 </span>            <span style="color:#000000; font-weight:bold">return</span> self<span style="color:#000000">.</span><span style="color:#010181">__warg</span><span style="color:#000000">() &gt;</span> <span style="color:#2928ff">5</span> <span style="color:#000000; font-weight:bold">or</span> actor<span style="color:#000000">.</span>is_staff
<span style="color:#555555">  14 </span>
<span style="color:#555555">  15 </span>
<span style="color:#555555">  16 </span><span style="color:#000000; font-weight:bold">class</span> <span style="color:#010181">Foo</span><span style="color:#000000">(</span>models<span style="color:#000000">.</span>Model<span style="color:#000000">,</span> FooPermissions<span style="color:#000000">):</span>
<span style="color:#555555">  17 </span>    <span style="color:#838183; font-style:italic"># fields, managers, etc...</span>
</pre>

<p>First we created a permissions mixin, subclassing a <code>PermissionMixin</code> I&#8217;ll show it to you in a minute, and mixed it with our model definition. This way we keep permissions seperate at the source level. Also, for instance <code>__warg</code> method will not be <a href="http://www.python.org/doc/current/tutorial/classes.html#private-variables">accessible</a> from our model. You can do anything inside your permissions class, you can even have side effects if you like. all you have to do is to follow a naming convention for your permission methods. Here is the <code>PermissionMixin</code> class:</p>

<pre><span style="color:#555555">   1 </span><span style="color:#000000; font-weight:bold">from</span> django<span style="color:#000000">.</span>contrib<span style="color:#000000">.</span>auth<span style="color:#000000">.</span>models <span style="color:#000000; font-weight:bold">import</span> User
<span style="color:#555555">   2 </span>
<span style="color:#555555">   3 </span>
<span style="color:#555555">   4 </span><span style="color:#000000; font-weight:bold">class</span> <span style="color:#010181">PermissionError</span><span style="color:#000000">(</span><span style="color:#000000; font-weight:bold">StandardError</span><span style="color:#000000">):</span>
<span style="color:#555555">   5 </span>    <span style="color:#000000; font-weight:bold">pass</span>
<span style="color:#555555">   6 </span>
<span style="color:#555555">   7 </span>
<span style="color:#555555">   8 </span><span style="color:#000000; font-weight:bold">class</span> <span style="color:#010181">PermissionMixin</span><span style="color:#000000">(</span><span style="color:#830000">object</span><span style="color:#000000">):</span>
<span style="color:#555555">   9 </span>    <span style="color:#000000; font-weight:bold">def</span> <span style="color:#010181">attempt</span><span style="color:#000000">(</span>self<span style="color:#000000">,</span> action<span style="color:#000000">,</span> actor<span style="color:#000000">,</span> msg<span style="color:#000000">=</span><span style="color:#000000; font-weight:bold">None</span><span style="color:#000000">):</span>
<span style="color:#555555">  10 </span>        <span style="color:#000000; font-weight:bold">return</span> PermissionMixin<span style="color:#000000">.</span><span style="color:#010181">_attempt</span><span style="color:#000000">(</span>self<span style="color:#000000">,</span> action<span style="color:#000000">,</span> actor<span style="color:#000000">,</span> msg<span style="color:#000000">=</span><span style="color:#000000; font-weight:bold">None</span><span style="color:#000000">)</span>
<span style="color:#555555">  11 </span>
<span style="color:#555555">  12 </span>    <span style="color:#000000">&#64;</span><span style="color:#830000">classmethod</span>
<span style="color:#555555">  13 </span>    <span style="color:#000000; font-weight:bold">def</span> <span style="color:#010181">cls_attempt</span><span style="color:#000000">(</span>cls<span style="color:#000000">,</span> action<span style="color:#000000">,</span> actor<span style="color:#000000">,</span> msg<span style="color:#000000">=</span><span style="color:#000000; font-weight:bold">None</span><span style="color:#000000">):</span>
<span style="color:#555555">  14 </span>        <span style="color:#000000; font-weight:bold">return</span> PermissionMixin<span style="color:#000000">.</span><span style="color:#010181">_attempt</span><span style="color:#000000">(</span>cls<span style="color:#000000">,</span> action<span style="color:#000000">,</span> actor<span style="color:#000000">,</span> msg<span style="color:#000000">=</span><span style="color:#000000; font-weight:bold">None</span><span style="color:#000000">)</span>
<span style="color:#555555">  15 </span>
<span style="color:#555555">  16 </span>    <span style="color:#000000">&#64;</span><span style="color:#830000">staticmethod</span>
<span style="color:#555555">  17 </span>    <span style="color:#000000; font-weight:bold">def</span> <span style="color:#010181">_attempt</span><span style="color:#000000">(</span>obj<span style="color:#000000">,</span> action<span style="color:#000000">,</span> actor<span style="color:#000000">,</span> msg<span style="color:#000000">):</span>
<span style="color:#555555">  18 </span>        <span style="color:#000000; font-weight:bold">if</span> actor<span style="color:#000000">.</span>__class__ <span style="color:#000000">!=</span> User <span style="color:#000000; font-weight:bold">or not</span> <span style="color:#830000">isinstance</span><span style="color:#000000">(</span>action<span style="color:#000000">,</span> basestring<span style="color:#000000">):</span>
<span style="color:#555555">  19 </span>            <span style="color:#000000; font-weight:bold">raise</span> <span style="color:#000000; font-weight:bold">TypeError</span>
<span style="color:#555555">  20 </span>        <span style="color:#000000; font-weight:bold">if</span> <span style="color:#830000">getattr</span><span style="color:#000000">(</span>obj<span style="color:#000000">,</span> <span style="color:#ff0000">'allows_%s_for'</span> <span style="color:#000000">%</span> action<span style="color:#000000">.</span><span style="color:#010181">lower</span><span style="color:#000000">().</span><span style="color:#010181">replace</span><span style="color:#000000">(</span><span style="color:#ff0000">' '</span><span style="color:#000000">,</span>
<span style="color:#555555">  21 </span>                                                                 <span style="color:#ff0000">'_'</span><span style="color:#000000">))(</span>actor<span style="color:#000000">):</span>
<span style="color:#555555">  22 </span>            <span style="color:#000000; font-weight:bold">return True</span>
<span style="color:#555555">  23 </span>        <span style="color:#000000; font-weight:bold">else</span><span style="color:#000000">:</span>
<span style="color:#555555">  24 </span>            <span style="color:#000000; font-weight:bold">if</span> msg <span style="color:#000000; font-weight:bold">is None</span><span style="color:#000000">:</span>
<span style="color:#555555">  25 </span>                msg <span style="color:#000000">=</span> u<span style="color:#ff0000">'%s doesn</span><span style="color:#ff00ff">\'</span><span style="color:#ff0000">t have permission to %s %s'</span> <span style="color:#000000">% (</span>actor<span style="color:#000000">.</span>username<span style="color:#000000">,</span>
<span style="color:#555555">  26 </span>                                                                 action<span style="color:#000000">.</span><span style="color:#010181">lower</span><span style="color:#000000">(),</span>
<span style="color:#555555">  27 </span>                                                                 <span style="color:#830000">repr</span><span style="color:#000000">(</span>obj<span style="color:#000000">))</span>
<span style="color:#555555">  28 </span>            <span style="color:#000000; font-weight:bold">raise</span> <span style="color:#010181">PermissionError</span><span style="color:#000000">(</span>msg<span style="color:#000000">)</span>
</pre>

<p>When you want to check for a permission you just need it&#8217;s key (name of the action) and have your <code>User</code> at hand:</p>

<pre><span style="color:#838183; font-style:italic"># Check a permission on a model:</span>
Foo<span style="color:#000000">.</span><span style="color:#010181">cls_attempt</span><span style="color:#000000">(</span><span style="color:#ff0000">'bar'</span><span style="color:#000000">,</span> user<span style="color:#000000">)</span>

<span style="color:#838183; font-style:italic"># Check a permission on an instance:</span>
foo<span style="color:#000000">.</span><span style="color:#010181">attempt</span><span style="color:#000000">(</span><span style="color:#ff0000">'baz'</span><span style="color:#000000">,</span> user<span style="color:#000000">)</span>
</pre>

<p>Notice that we are still using <code>Permission</code>s from <code>auth</code>. Our <code>PermissionMixin</code> can do complex logic, but its hard-coded. We still need something like <code>Permission</code>s for dynamic behaviour. Why not use what&#8217;s built-in?</p>

<p>You can find <code>PermissionMixin</code>&#8216;s code at <a href="http://www.djangosnippets.org/snippets/1502/">Django snipplets</a>.</p>

<h3>Conclusion</h3>

<p>Before employing a similar mechanism, you should think hard if you absolutely positively need it. Maybe you can simplify your UI? Maybe there is a nice tradeoff between code complexity and interactivity of your application? Maybe you can move this logic into <code>model.save()</code> or <code>form.save()</code> or <code>form.clean()</code>? Or maybe your code will be best organized if you use <code>PermissionMixin</code>s.</p>

<p>I just wanted to show that you can build on <code>auth</code>&#8216;s <code>Permission</code>s. Just don&#8217;t get discouraged when you find out <em>you can&#8217;t do x out of the box</em>. Be it permissions or some model magic or making something available in your templates; Django is Python, it can be extended easily.</p>

<hr />

<p><strong>1</strong>: Provided you have <code>auth</code> app installed of course.</p>

<p><strong>2</strong>: Ask yourself; &#8220;Is this <strong>really</strong> a must?&#8221;, and not only for permission related complications.</p>


<p>Related posts:<ol><li><a href='http://www.muhuk.com/2009/05/django-formfieldset/' rel='bookmark' title='Permanent Link: django-formfieldset'>django-formfieldset</a></li>
<li><a href='http://www.muhuk.com/2009/07/django-renderformplain/' rel='bookmark' title='Permanent Link: django-renderformplain'>django-renderformplain</a></li>
<li><a href='http://www.muhuk.com/2009/09/django-fixtures/' rel='bookmark' title='Permanent Link: Django Fixtures'>Django Fixtures</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://www.muhuk.com/2009/05/django-permission-system/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Getting A Little Further Than Hello World With Qooxdoo</title>
		<link>http://www.muhuk.com/2008/10/getting-a-little-further-than-hello-world-with-qooxdoo/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=getting-a-little-further-than-hello-world-with-qooxdoo</link>
		<comments>http://www.muhuk.com/2008/10/getting-a-little-further-than-hello-world-with-qooxdoo/#comments</comments>
		<pubDate>Fri, 17 Oct 2008 17:14:54 +0000</pubDate>
		<dc:creator>Atamert Ölçgen</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[hello world]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[object oriented]]></category>
		<category><![CDATA[qooxdoo]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://www.muhuk.com/?p=39</guid>
		<description><![CDATA[I have mentioned about Rich Internet Applications in a previous post. Qooxdoo is an AJAX framework, especially strong on creating desktop-like GUI&#8217;s. It allows you to build your interface in an object oriented manner. Like tkinter or GTK, and much more than the others it is like swing. Qooxdoo is well documented and has a [...]]]></description>
			<content:encoded><![CDATA[<p>I have <a href="http://www.muhuk.com/2008/09/v-for-volatile/">mentioned</a> about <a href="http://en.wikipedia.org/wiki/Rich_internet_application">Rich Internet Applications</a> in a previous post. <a href="http://qooxdoo.org">Qooxdoo</a> is an AJAX framework, especially strong on creating desktop-like GUI&#8217;s. It allows you to build your interface in an object oriented manner. Like <a href="http://wiki.python.org/moin/TkInter">tkinter</a> or <a href="http://www.gtk.org/">GTK</a>, and much more than the others it is like <a href="http://en.wikipedia.org/wiki/Java_Swing">swing</a>.</p>

<p>Qooxdoo is <a href="http://demo.qooxdoo.org/0.8.x/apiviewer/">well</a> <a href="http://qooxdoo.org/documentation">documented</a> and has a clean API. It <a href="http://qooxdoo.org/download">comes</a> with a Python program to help with builds. Because it is such a big framework you test on a partially compiled source and when finished this build program generates a single (actually two, it also generates a loader), compact (and somewhat obfuscated) file for performance. I strongly advise you to give it a try. The following is a small introductory tutorial. It aims to go little further than Hello World. <strong>This is not a tutorial explaining object oriented programming concepts, I assume you are already fluent in <a href="http://en.wikipedia.org/wiki/Object-oriented_programming">OOP</a></strong>.</p>

<h3>Create The Skeleton</h3>

<div id="attachment_52" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.muhuk.com/wp-content/uploads/2008/10/snapshot2.jpeg"><img src="http://www.muhuk.com/wp-content/uploads/2008/10/snapshot2-300x77.jpg" alt="Screenshot of finished application" title="Screenshot of finished application" width="300" height="77" class="size-medium wp-image-52" /></a><p class="wp-caption-text">Screenshot of finished application</p></div>

<p>We&#8217;ll create a simple calculator-like application. I am assuming you have downloaded (latest version is 0.8 for today) and extracted the source into a directory. Let&#8217;s call it <code>qxtut</code>. The first thing we will do is to create a skeleton of our application with the following command;</p>

<pre><code>./qooxdoo-0.8-sdk/tool/bin/create-application.py --name basicmath
</code></pre>

<p>This command has created the following directory structure under ./basicmath;</p>

<pre><code>qxtut/
  qooxdoo-0.8-sdk/
  basicmath/
    source/
    build/
    cache/
    api/
    config.json
    Manifest.json
</code></pre>

<p>Well, some of the directories (<code>build</code> &amp; <code>cache</code>) are not there yet. But as we go on they will appear, I just wanted you to see how the application is organized. <code>config.json</code> and <code>Manifest.json</code> files are configuration files for the build tool. We don&#8217;t need to change them for this tutorial, but you are welcome to check their contents.</p>

<p>Let us build our source for the first time;</p>

<pre><code>cd basicmath
./generate.py source
</code></pre>

<p>Now if you open <code>./source/index.html</code> in your browser you can see a Hello World application in action. We&#8217;ll replace this with our own program. But before we proceed I&#8217;d like to point out a few things;</p>

<ul>
<li>When we define our classes, we call a class method <code>define</code> on <code>qx.Class</code> and pass our class&#8217; name (along with its namespace) and its contents as arguments. We don&#8217;t define our classes using prototypes, in order to take advantage of Qooxdoo&#8217;s object oriented programming features.</li>
<li>Qooxdoo supports <a href="http://qooxdoo.org/documentation/0.8/classes#inheritance">single inheritance</a> (with <a href="http://qooxdoo.org/documentation/0.8/mixins">mixins</a>). We define our base class, if we have one, using <code>extend</code> key.</li>
<li>Instance members are defined inside the <code>members</code> key and class members are defined inside the <code>statics</code> key.</li>
<li><code>construct</code> and <code>destruct</code> are two special functions for initialization and cleanup of the class.</li>
<li>Qooxdoo supports [properties](http://en.wikipedia.org/wiki/Property_(programming&#41;) as well, but it is outside of this tutorial&#8217;s scope.</li>
<li>Finally, &#8220;<code>#asset(basicmath/*)</code>&#8221; line tells the build program to include assets (images etc) in <code>qxtut/basicmath/source/resource/basicmath</code> directory.</li>
</ul>

<h3>Custom Classes</h3>

<p>Let&#8217;s start building our application now. Here is a compact version of Application.js;</p>

<pre><code>/* ************************************************************************
#asset(basicmath/*)
************************************************************************ */

qx.Class.define("basicmath.Application", {
    extend: qx.application.Standalone,
    members: {
        main: function()
        {
            this.base(arguments);
            if (qx.core.Variant.isSet("qx.debug", "on")) {
                qx.log.appender.Native;
                qx.log.appender.Console;
            }
            // Our code will come here
        }
    }
});
</code></pre>

<p>Now we will create a custom class named <code>Operation</code>. This class will take two operands and perform an operation on them, and then later we will add it the ability to report the result of the operation. Paste this as <code>Operation.js</code>;</p>

<pre><code>/* ************************************************************************
#asset(basicmath/*)
************************************************************************ */

qx.Class.define("basicmath.Operation", {
    extend: qx.ui.container.Composite,
    construct: function() {
        this.base(arguments);
        var layout = new qx.ui.layout.HBox(6);
        this.setLayout(layout);
        this.operand1 = new qx.ui.form.TextField("0");
        this.operator = new qx.ui.form.SelectBox();
        this.operator.add(new qx.ui.form.ListItem("add"));
        this.operator.add(new qx.ui.form.ListItem("subtract"));
        this.operator.add(new qx.ui.form.ListItem("multiply"));
        this.operator.add(new qx.ui.form.ListItem("divide"));
        this.operand2 = new qx.ui.form.TextField("0");
        this.result = new qx.ui.basic.Label("0");
        this.add(this.operand1);
        this.add(this.operator);
        this.add(this.operand2);
        this.add(this.result);
    },
    members: {
        operand1: null,
        operator: null,
        operand2: null,
        result: null
    }
});
</code></pre>

<p>The code should be self explanatory. Notice here, we define <code>operand1</code>, <code>operator</code>, <code>operand2</code> and <code>result</code> as members of the class. Also notice we initialize those members in the constructor and not in the class body<sup>1</sup>. This is because their respected values (classes) are derived from the non-primitive <code>Object</code> type. Therefore if we have assigned them a non-primitive type (such as the array [1, 2, 3]) in the members section; all instances would point to the same object.</p>

<p>Let us now plug this object in our application. Replace the comment line &#8220;<code>// Our code will come here</code>&#8221; with the following;</p>

<pre><code>this.getRoot().add(new basicmath.Operation);
</code></pre>

<p>Now, when we compile the source and run index.html we should see our widgets in place.</p>

<div id="attachment_51" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.muhuk.com/wp-content/uploads/2008/10/snapshot1.jpeg"><img src="http://www.muhuk.com/wp-content/uploads/2008/10/snapshot1-300x40.jpg" alt="Screenshot of an Operation widget we have just created" title="Screenshot of an Operation widget we have just created" width="300" height="40" class="size-medium wp-image-51" /></a><p class="wp-caption-text">Screenshot of an Operation widget we have just created</p></div>

<h3>Simple Behaviour</h3>

<p>We want our widget to calculate the operation and show us the result. Let&#8217;s update the members section of <code>Operation</code> with the following;</p>

<pre><code>members: {
    operand1: null,
    operator: null,
    operand2: null,
    result: null,
    updateResult: function() {
        var v1 = this.cleanField(this.operand1);
        var v2 = this.cleanField(this.operand2);
        var r;
        switch(this.operator.getValue()) {
            case "add": r = v1+v2; break;
            case "subtract": r = v1-v2; break;
            case "multiply": r = v1*v2; break;
            case "divide": r = v1/v2; break;
        }
        this.result.setContent(String(r));
        this.operand1.setValue(String(v1));
        this.operand2.setValue(String(v2));
    },
    cleanField: function(field) {
        var val = parseInt(field.getValue());
        return isNaN(val) ? 0 : val;
    }
}
</code></pre>

<p>We have added two functions here <code>updateResult</code> and <code>cleanField</code>. Now we make use of them, change the <code>construct</code> with the following;</p>

<pre><code>construct: function() {
    this.base(arguments);
    var layout = new qx.ui.layout.HBox(6);
    this.setLayout(layout);
    this.operand1 = new qx.ui.form.TextField("0");
    this.operand1.addListener("input", this.updateResult, this);
    this.operator = new qx.ui.form.SelectBox();
    this.operator.add(new qx.ui.form.ListItem("add"));
    this.operator.add(new qx.ui.form.ListItem("subtract"));
    this.operator.add(new qx.ui.form.ListItem("multiply"));
    this.operator.add(new qx.ui.form.ListItem("divide"));
    this.operator.addListener("changeValue", this.updateResult, this);
    this.operand2 = new qx.ui.form.TextField("0");
    this.operand2.addListener("input", this.updateResult, this);
    this.result = new qx.ui.basic.Label("0");
    this.add(this.operand1);
    this.add(this.operator);
    this.add(this.operand2);
    this.add(this.result);
}
</code></pre>

<p>We just added these three listeners to update the result when an operand or the operator changes;</p>

<pre><code>this.operand1.addListener("input", this.updateResult, this);
this.operator.addListener("changeValue", this.updateResult, this);
this.operand2.addListener("input", this.updateResult, this);
</code></pre>

<p>The last parameter (<code>this</code>) for <code>addListener</code> (even though it is sometimes unnecessary) set the scope within the listener code (the second parameter). Qooxdoo handles most of the binding automatically, I think this is included for flexibility.</p>

<p>Let&#8217;s compile and run again. The result of the operation should update as you change the values now.</p>

<h3>Events To Tie All Together</h3>

<p>I&#8217;ll give you the finished code first and then we can go over the details. Here is <code>Operation.js</code>;</p>

<pre><code>/* ************************************************************************
#asset(basicmath/*)
#asset(qx/icon/Oxygen/*)
************************************************************************ */

qx.Class.define("basicmath.Operation", {
    extend: qx.ui.container.Composite,
    construct: function() {
        this.base(arguments);
        var layout = new qx.ui.layout.HBox(6);
        this.setLayout(layout);
        this.operand1 = new qx.ui.form.TextField("0");
        this.operand1.addListener("input", this.updateResult, this);
        this.operator = new qx.ui.form.SelectBox();
        this.operator.add(new qx.ui.form.ListItem("add"));
        this.operator.add(new qx.ui.form.ListItem("subtract"));
        this.operator.add(new qx.ui.form.ListItem("multiply"));
        this.operator.add(new qx.ui.form.ListItem("divide"));
        this.operator.addListener("changeValue", this.updateResult, this);
        this.operand2 = new qx.ui.form.TextField("0");
        this.operand2.addListener("input", this.updateResult, this);
        this.result = new qx.ui.form.TextField("0");
        this.result.setReadOnly(true);
        var close_button = new qx.ui.form.Button(
            null,
            "qx/icon/Oxygen/16/actions/application-exit.png"
        );
        close_button.addListener("execute", function(e) {
            this.fireDataEvent(
                "changeResult",
                0,
                parseFloat(this.result.getValue()),
                false
            );
            this.destroy();
        }, this);
        this.add(this.operand1);
        this.add(this.operator);
        this.add(this.operand2);
        this.add(new qx.ui.basic.Label("="));
        this.add(this.result);
        this.add(new qx.ui.core.Spacer(8));
        this.add(close_button);
    },
    events: {
        "changeResult": "qx.event.type.Data"
    },
    members: {
        operand1: null,
        operator: null,
        operand2: null,
        result: null,
        updateResult: function() {
            var v1 = this.cleanField(this.operand1);
            var v2 = this.cleanField(this.operand2);
            var r;
            switch(this.operator.getValue()) {
                case "add": r = v1+v2; break;
                case "subtract": r = v1-v2; break;
                case "multiply": r = v1*v2; break;
                case "divide": r = v1/v2; break;
            }
            this.fireDataEvent("changeResult",
                r,
                parseFloat(this.result.getValue()),
                false
            );
            this.result.setValue(String(r));
            this.operand1.setValue(String(v1));
            this.operand2.setValue(String(v2));
        },
        cleanField: function(field) {
            var val = parseInt(field.getValue());
            return isNaN(val) ? 0 : val;
        }
    }
});
</code></pre>

<p>And <code>Application.js</code>;</p>

<pre><code>/* ************************************************************************
#asset(basicmath/*)
#asset(qx/icon/Oxygen/*)
************************************************************************ */

qx.Class.define("basicmath.Application", {
    extend : qx.application.Standalone,
    members : {
        main : function()
        {
            this.base(arguments);
            if (qx.core.Variant.isSet("qx.debug", "on")) {
                qx.log.appender.Native;
                qx.log.appender.Console;
            }
            var layout = new qx.ui.container.Composite(
                new qx.ui.layout.VBox(8)
            );
            var layout_footer = new qx.ui.container.Composite(
                new qx.ui.layout.HBox(6)
            );
            var total = new qx.ui.basic.Label("0");
            var add_button = new qx.ui.form.Button(
                "Add New",
                "qx/icon/Oxygen/16/actions/list-add.png"
            );
            add_button.addListener("execute", function(e) {
                var new_operation = new basicmath.Operation();
                layout.addBefore(new_operation, layout_footer);
                new_operation.addListener("changeResult", function(e) {
                    var old_total = parseFloat(total.getContent());
                    var new_total = old_total - e.getOldData() + e.getData();
                    total.setContent(String(new_total));
                }, this);
            }, this);
            layout_footer.add(add_button);
            layout_footer.add(total);
            layout.add(layout_footer);
            add_button.execute();
            this.getRoot().add(layout);
        }
    }
});
</code></pre>

<p>Let&#8217;s go top-down and begin with the changes in the <code>Application.js</code>;</p>

<pre><code>var layout = new qx.ui.container.Composite(new qx.ui.layout.VBox(8));
this.getRoot().add(layout);
</code></pre>

<p>We don&#8217;t necessarily need to subclass everytime we need specialized behaviour. Since I had intented to re-use <code>Operation</code> I have it as a seperate class. But for the layout of the application I just instanciated some classes and tweaked them inside <code>Application.main</code>. <code>layout</code> here is the topmost widget, we will put everything else in it. Basically one or more <code>Operation</code>&#8216;s and a footer to dispay the grand total. <code>VBox</code> layout is by the way a layout manager that stacks children vertically, and a <code>HBox</code> stacks horizontally.</p>

<pre><code>var layout = new qx.ui.container.Composite(new qx.ui.layout.VBox(8));
var layout_footer = new qx.ui.container.Composite(new qx.ui.layout.HBox(6));
var total = new qx.ui.basic.Label("0");
var add_button = new qx.ui.form.Button(
    "Add New",
    "qx/icon/Oxygen/16/actions/list-add.png"
);
add_button.addListener("execute", function(e) {
    var new_operation = new basicmath.Operation();
    layout.addBefore(new_operation, layout_footer);
    new_operation.addListener("changeResult", function(e) {
        var old_total = parseFloat(total.getContent());
        var new_total = old_total - e.getOldData() + e.getData();
        total.setContent(String(new_total));
    }, this);
}, this);
</code></pre>

<p>We define a label <code>total</code> to hold the grand total of all operations and an add button for new operations. Notice the closures work on 7th line. Although we limit ourselves a little bit to take advantage of OOP, we are still in a dynamic environment. Finally we tie all these components together and finally add the <code>layout</code> to the application root.</p>

<pre><code>add_button.execute();
</code></pre>

<p>This instantiates the first <code>Operation</code> for us. We execute the button instead of creating the widget programmatically to avoid the code duplication (see the &#8220;execute&#8221; listener on the <code>add_button</code>).</p>

<p>Now let&#8217;s take a look at the changes in <code>Operation.js</code>. I have replaced the <code>result</code> <code>Label</code> with a <code>TextField</code> (remember to run &#8220;<code>generate.py source</code>&#8221; each time dependencies change). I wanted to take advantage of the getOldData function on <code>TextField</code>&#8216;s <code>changeValue</code> event. But appereantly it doesn&#8217;t supply the old data. But I kept it as a <code>TextField</code> anyway, setting it read-only.</p>

<p>Then I decided that <code>Operation</code> should signal for a result change (maybe this is more politically correct) and added a custom event <code>changeResult</code> on it.</p>

<pre><code>events: {
    "changeResult": "qx.event.type.Data"
}
</code></pre>

<p>This event is fired inside <code>Operation.updateResult</code>;</p>

<pre><code>this.fireDataEvent(
    "changeResult",
    r,
    parseFloat(this.result.getValue()),
    false
);
</code></pre>

<p>The second parameter is returned from e.getData() and the third is from e.getOldData(). Therefore we can calculate the grand total without iterating all <code>Operation</code>s;</p>

<pre><code>var new_total = old_total - e.getOldData() + e.getData();
</code></pre>

<p>An important point here is to fire <code>changeResult</code> to correct the grand total before we destroy an <code>Operation</code>;</p>

<pre><code>close_button.addListener("execute", function(e) {
    this.fireDataEvent(
        "changeResult",
        0,
        parseFloat(this.result.getValue()),
        false
    );
    this.destroy();
}, this);
</code></pre>

<h3>Wrapping Up</h3>

<p>Now it should work correctly, if I haven&#8217;t made a typo of course. Let us build it with;</p>

<pre><code>./generate.py build
</code></pre>

<p>It generates a loader (~150kb) and an application script (~400kb). You don&#8217;t need the Qooxdoo source anymore, you can just upload the contents of the <code>build</code> directory and your application would run.</p>

<p>This concludes my <em>a little further than Hello World</em> tutorial. If you find errors or typos, or have any questions please leave a comment here or contact me at muhuk@jabber.org.</p>

<hr />

<p><strong>1</strong>: Here is an explanation in <a href="http://qooxdoo.org/documentation/0.8/classes#instance_members">Qooxdoo manual</a>.</p>


<p>Related posts:<ol><li><a href='http://www.muhuk.com/2009/04/using-layouts-in-qooxdoo-index/' rel='bookmark' title='Permanent Link: Using Layouts In Qooxdoo &#8211; Index'>Using Layouts In Qooxdoo &#8211; Index</a></li>
<li><a href='http://www.muhuk.com/2009/01/using-layouts-in-qooxdoo-part-1/' rel='bookmark' title='Permanent Link: Using Layouts In Qooxdoo &#8211; Part 1'>Using Layouts In Qooxdoo &#8211; Part 1</a></li>
<li><a href='http://www.muhuk.com/2009/02/using-layouts-in-qooxdoo-part-2-vbox-layout/' rel='bookmark' title='Permanent Link: Using Layouts In Qooxdoo &#8211; Part 2: VBox Layout'>Using Layouts In Qooxdoo &#8211; Part 2: VBox Layout</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://www.muhuk.com/2008/10/getting-a-little-further-than-hello-world-with-qooxdoo/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
	</channel>
</rss>
