<?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>Coherent</title>
	<atom:link href="http://coherentjs.org/feed/" rel="self" type="application/rss+xml" />
	<link>http://coherentjs.org</link>
	<description>A UI Framework for the Web</description>
	<lastBuildDate>Fri, 12 Feb 2010 06:05:35 +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>Performance Tuning</title>
		<link>http://coherentjs.org/development/performance-tuning/</link>
		<comments>http://coherentjs.org/development/performance-tuning/#comments</comments>
		<pubDate>Fri, 12 Feb 2010 06:05:32 +0000</pubDate>
		<dc:creator>jeff</dc:creator>
				<category><![CDATA[Development]]></category>

		<guid isPermaLink="false">http://coherentjs.org/?p=314</guid>
		<description><![CDATA[So I&#8217;m deep in the middle of some performance tuning work for the release of Coherent 3.0. Everyone knows that optimising Javascript is a bit of a black art, but I almost think I&#8217;m doing something wrong.

Here are the performance metrics for Coherent 2.0 running on IE 8 (in a VM):

     [...]]]></description>
			<content:encoded><![CDATA[<p>So I&#8217;m deep in the middle of some performance tuning work for the release of Coherent 3.0. Everyone knows that optimising Javascript is a bit of a black art, but I <strong>almost</strong> think I&#8217;m doing something wrong.</p>

<p>Here are the performance metrics for Coherent 2.0 running on IE 8 (in a VM):</p>

<pre><code>      direct:  5.688s for 50 iterations  (Avg: 113.755ms)
     derived:  6.086s for 50 iterations  (Avg: 121.720ms)
     methods:  9.793s for 50 iterations  (Avg: 195.860ms)
      notify: 10.946s for 50 iterations  (Avg: 218.910ms)
notify class:  6.785s for 500 iterations (Avg:  13.570ms)
</code></pre>

<p>Coherent&#8217;s never been a stellar performer in Internet Explorer. That&#8217;s something of an understatement, but I&#8217;ve always felt the blame rested largely on IE&#8217;s craptacular Javascript engine.</p>

<p>Now, I&#8217;m not so sure.</p>

<p>Below are the same run times for the same performance tests, but this time the tests are running against the new optimised code in Coherent 3.0:</p>

<pre><code>      direct:  4.309s for 50 iterations  (Avg:  86.170ms)
     derived:  0.625s for 50 iterations  (Avg:  12.500ms)
     methods:  0.910s for 50 iterations  (Avg:  18.205ms)
      notify:  8.356s for 50 iterations  (Avg: 167.110ms)
notify class:  4.547s for 500 iterations (Avg:   9.094ms)
</code></pre>

<p>Clearly, I&#8217;m doing <strong>something</strong> right. All the unit tests still pass. And I&#8217;m getting a 9.7&times; speed improvement for derived property access — that&#8217;s when accessing properties of a class derived from <code>coherent.KVO</code>, a 10.7&times; speed improvement for calling getter and setter methods, and significant 1.3&times; to 1.5&times; improvement for the other operations.</p>

<p>The same code running in other browsers (Safari 4.0, WebKit nightly, Firefox 3.5 and Firefox 3.6) all see speed improvements between 1.3&times; and 2.0&times;, but nothing nearly as dramatic as IE.</p>

<p>Below are the performance numbers from WebKit nightly running Coherent 2.0:</p>

<pre><code>      direct: 304.750ms for 100 iterations  (Avg: 3.047ms)
     derived: 324.750ms for 100 iterations  (Avg: 3.248ms)
     methods: 286.250ms for 100 iterations  (Avg: 2.862ms)
      notify: 742.750ms for 100 iterations  (Avg: 7.428ms)
notify class: 257.750ms for 1000 iterations (Avg: 0.258ms)
</code></pre>

<p>And WebKit nightly running Coherent 3.0:</p>

<pre><code>      direct: 195.500ms for 100 iterations  (Avg: 1.955ms)
     derived: 204.000ms for 100 iterations  (Avg: 2.040ms)
     methods: 213.500ms for 100 iterations  (Avg: 2.135ms)
      notify: 468.750ms for 100 iterations  (Avg: 4.688ms)
notify class: 162.500ms for 1000 iterations (Avg: 0.163ms)
</code></pre>

<p>This is just the result of changes to the core methods of <code>coherent.KVO</code> and <code>coherent.KeyInfo</code>. Of course, there&#8217;s still more performance tuning to come. But I don&#8217;t think I&#8217;ll have anything this dramatic to report again&#8230;</p>
<img src="http://coherentjs.org/wordpress/?ak_action=api_record_view&id=314&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://coherentjs.org/development/performance-tuning/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Resurrected Old Content</title>
		<link>http://coherentjs.org/overview/resurrected-old-content/</link>
		<comments>http://coherentjs.org/overview/resurrected-old-content/#comments</comments>
		<pubDate>Wed, 23 Dec 2009 05:36:22 +0000</pubDate>
		<dc:creator>jeff</dc:creator>
				<category><![CDATA[Overview]]></category>

		<guid isPermaLink="false">http://coherentjs.org/?p=306</guid>
		<description><![CDATA[As part of getting the new coherentjs.org Web site ready, I dragged out a back up of the original content. The import for Wordpress went relatively smoothly, but it&#8217;s pretty clear this content either needs to be cleaned up or rewritten.

The biggest problem is that a lot of it is simply not accurate any more. [...]]]></description>
			<content:encoded><![CDATA[<p>As part of getting the new coherentjs.org Web site ready, I dragged out a back up of the original content. The import for Wordpress went relatively smoothly, but it&#8217;s pretty clear this content either needs to be cleaned up or rewritten.</p>

<p>The biggest problem is that a lot of it is simply not accurate any more. However, I&#8217;m going to leave it there for historical interest — I&#8217;m a bit surprised reading about my first efforts back in 2005. Maybe it will interest other developers too.</p>

<p>Probably the most important feature of the new site is the <a href="/docs/api">API documentation</a>. This is greatly expanded from the original documentation from Coherent 1.0. And it will only get better as I continue to review the code and add doc comments.</p>
<img src="http://coherentjs.org/wordpress/?ak_action=api_record_view&id=306&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://coherentjs.org/overview/resurrected-old-content/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Declarative Syntax for Child Widgets</title>
		<link>http://coherentjs.org/development/declarative-syntax-for-child-widgets/</link>
		<comments>http://coherentjs.org/development/declarative-syntax-for-child-widgets/#comments</comments>
		<pubDate>Thu, 22 May 2008 04:34:35 +0000</pubDate>
		<dc:creator>jeff</dc:creator>
				<category><![CDATA[Development]]></category>

		<guid isPermaLink="false">http://localhost:8888/?p=25</guid>
		<description><![CDATA[One of my goals for Coherent 1.1 is the option of using a declarative syntax to set up child widgets. This would greatly simplify the average init method and make the code a bit clearer and easier to understand.


Essentially, I&#8217;m thinking of something like the following:

sample.MyWidget= Class.create(coherent.Widget, {

    init: function()
   [...]]]></description>
			<content:encoded><![CDATA[<p>One of my goals for Coherent 1.1 is the option of using a declarative syntax to set up child widgets. This would greatly simplify the average <code>init</code> method and make the code a bit clearer and easier to understand.
<span id="more-173"></span></p>

<p>Essentially, I&#8217;m thinking of something like the following:</p>

<pre><code>sample.MyWidget= Class.create(coherent.Widget, {

    init: function()
    {},

    title: TextWidget('div.header em', {

                htmlKeyPath: '*.selection.title',

                onclick: function(event)
                {
                    ... handle clicking on the title ...
                },

                ... etc ...

            }),

    nextButton: Widget('div.controls button.next', {

                    onclick: function(event)
                    {
                        ... go to the next image ...
                    }

                }),

    ... etc ...
});
</code></pre>

<p>Just before calling <code>init</code>, the Widget framework should create sub-widgets for <code>title</code> and <code>nextButton</code>. For the <code>title</code>, its <code>html</code> binding would be connected to the key path <code>selection.title</code> from the outer widget. Additionally, a click handler would be created with the given method. The scope of the <code>onclick</code> method for <code>title</code> would be <code>MyWidget</code> rather than the actual <code>TextWidget</code>.</p>

<p>Using the new Selector library, you could create widgets based on any CSS query rather than just a direct descendant or ID. I don&#8217;t think there&#8217;s any need to have sub-widgets within the sub-widgets. If that&#8217;s what you&#8217;re looking for, you <em>probably</em> want to look at creating a widget rather than declaring the structure.</p>

<p>To be backward compatible, the node specifier (<code>div.header em</code>) should be checked to see whether it is an ID. This means that <code>#foo</code> would be equivalent to simply <code>foo</code>. Because presently, Coherent allows you to specify the ID of the node as a string without the preceding hash. Perhaps I can generate a deprecation warning&#8230;</p>

<h3>Bindings and event handlers on sub-widgets</h3>

<p>The second parameter to the widget declarations is how you may specify bindings for the sub-widget as well as events to handle. This hash should contain either key path entries (e.g. <code>htmlKeyPath</code>) or event handler entries (e.g. <code>onclick</code>). Essentially, after finding the node via a selector query, Coherent will enumerate the keys in this hash and for keys with a string value, call <code>setAttribute</code> on the node with the key and value. For keys with a function value, Coherent will observe the event of the same name as the key after stripping the <code>on</code> prefix (e.g. <code>onclick</code> &#x21D2; <code>click</code>).</p>

<p>This is roughly similar to how the <a href="/2008/05/selectors-and-bindings"><code>setupNodeWithSelectors</code> method</a> works. So this seems like a reasonable approach.</p>

<h3>Changes to Coherent&#8217;s OOP model</h3>

<p>In order to make this work, I&#8217;d need to tweak Coherent&#8217;s OOP model a bit. Essentially, JavaScript assigns special meaning to using a function as the target of the <code>new</code> operator. What I&#8217;d be doing it taking advantage of this to branch and execute different code depending on how the <em>constructor</em> was invoked.</p>

<p>Instead of allowing the constructor to perform this double duty, what if Coherent shunted off non-constructor invocations of the constructor to a factory method? This factory method would be expected to return another function which could be invoked to create an instance of the class.</p>

<p>So consider the following class definition:</p>

<pre><code>sample.MyClass = Class.create({

    constructor: function(arg1, arg2)
    {
        this.prop1= arg1;
        this.prop2= arg2;
    },

    __factory__: function(arg2)
    {
        var klass= this;

        return function(arg1)
        {
            return new klass(arg1, arg2);
        }
    },

    // ... etc ...
});
</code></pre>

<p>Because the factory method would be inherited by sub-classes, there will have to be some slight magic under the covers. Basically, Coherent will invoke the factory method in the scope of the class itself, therefore <code>this</code> will be equal to the class on which the factory method was invoked rather than the class on which the factory method was defined.</p>

<p>This allows you to write code like the following:</p>

<pre><code>var foo= sample.MyClass('abc');
// ... later ...
var bar= foo('def');
</code></pre>

<p>If a class doesn&#8217;t define a <code>__factory__</code> member, I think Coherent should simply throw an Error. After all, you almost never get what you&#8217;re expecting in that case.</p>

<p>There&#8217;s no getting around the fact that writing a <code>__factory__</code> method will be something of a pain. But for the primary use of creating declarative sub-widgets, there need only be one factory on the base <code>Widget</code> class. All sub-classes of Widget will be able to use the default factory method, unless the sub-class has defined its own constructor with additional/different arguments.</p>

<p>Now all I need to do is code it&#8230;</p>
<img src="http://coherentjs.org/wordpress/?ak_action=api_record_view&id=173&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://coherentjs.org/development/declarative-syntax-for-child-widgets/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Favourable Reception for Coherent</title>
		<link>http://coherentjs.org/development/favourable-reception-for-coherent/</link>
		<comments>http://coherentjs.org/development/favourable-reception-for-coherent/#comments</comments>
		<pubDate>Sat, 03 May 2008 16:59:54 +0000</pubDate>
		<dc:creator>jeff</dc:creator>
				<category><![CDATA[Development]]></category>

		<guid isPermaLink="false">http://nerd.metrocat.org/2008/05/favourable-reception-for-coherent</guid>
		<description><![CDATA[I recently announced the upcoming release of Coherent 1.0 and I&#8217;ve been very pleased by the positive reception the library has received.

Lots of folks have come out of the woodwork to either say they&#8217;ve been looking for something like this for ages. I guess there are more fans of the Apple development model than I [...]]]></description>
			<content:encoded><![CDATA[<p>I recently announced the upcoming <a href="http://coherentjs.org/docs/release/coherent-10-release-candidate-1">release of Coherent 1.0</a> and I&#8217;ve been very pleased by the positive reception the library has received.</p>

<p>Lots of folks have come out of the woodwork to either say they&#8217;ve been looking for something like this for ages. I guess there are more fans of the Apple development model than I thought. And obviously a lot of us build Web applications either for a living or in our spare time.</p>

<p>As I&#8217;ve been working on some features I&#8217;ve planned for 1.1, I&#8217;ve run across some <a href="http://coherentjs.org/docs/development/selectors-and-bindings">strange problems with selectors</a> which seems to tie into <a href="http://ejohn.org/blog/thoughts-on-queryselectorall/">John Resig&#8217;s recent blog post about selectors</a>.</p>
<img src="http://coherentjs.org/wordpress/?ak_action=api_record_view&id=172&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://coherentjs.org/development/favourable-reception-for-coherent/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Selectors and Bindings</title>
		<link>http://coherentjs.org/development/selectors-and-bindings/</link>
		<comments>http://coherentjs.org/development/selectors-and-bindings/#comments</comments>
		<pubDate>Sat, 03 May 2008 03:40:42 +0000</pubDate>
		<dc:creator>jeff</dc:creator>
				<category><![CDATA[Development]]></category>

		<guid isPermaLink="false">http://localhost:8888/?p=24</guid>
		<description><![CDATA[One of the routine complaints about Coherent (yes, I&#8217;m talking about you Ryan) is the use of custom attributes. It seems that some people like their HTML pure, like it was back in the old days.


I see nothing wrong with the following mark up:

&#60;div id="outer"&#62;
    &#60;ul contentKeyPath="links.arrangedContent"&#62;
      [...]]]></description>
			<content:encoded><![CDATA[<p>One of the routine complaints about Coherent (yes, I&#8217;m talking about you Ryan) is the use of custom attributes. It seems that some people like their HTML pure, like it was back in the old days.
<span id="more-171"></span></p>

<p>I see nothing wrong with the following mark up:</p>

<pre><code>&lt;div id="outer"&gt;
    &lt;ul contentKeyPath="links.arrangedContent"&gt;
        &lt;li&gt;&lt;img srcKeyPath="*.iconHref" width="16" height="16"&gt;
            &lt;em textKeyPath="*.title"&gt;The Title&lt;/em&gt;
        &lt;/li&gt;
    &lt;/ul&gt;
&lt;/div&gt;
</code></pre>

<p>The offensive parts to the purists are <code>contentKeyPath</code>, <code>srcKeyPath</code>, and <code>textKeyPath</code>. Now browsers have always been <em>very</em> forgiving when it comes to extra attributes on nodes, but the purists think it&#8217;s sinful (or something) to take an expedient approach to adding useful information to the mark up.</p>

<p>I understand &mdash; really, I do &mdash; the whole separation of presentation from content and content from behaviour. However, in this particular case, I&#8217;m not actually marking up the content. I&#8217;m marking up the template for the content. To me, it makes a difference. But I understand I&#8217;ll never convince you if you&#8217;re already against custom attributes.</p>

<h3>An alternative to custom attributes</h3>

<p>So the other day I was kicking around an idea for an alternative syntax for describing the bindings between elements and the data model. Ideally I could have a format similar to the following:</p>

<pre><code>ul: {
    contentKeyPath: links.arrangedContent
},

ul li img: {
     srcKeyPath: *.iconHref
},

ul li em: {
    textKeyPath: *.title
}
</code></pre>

<p>Gosh, that looks just like JSON&#8230; so how about this:</p>

<pre><code>{
    'ul': {
        contentKeyPath: 'links.arrangedContent'
    },

    'ul li img': {
         srcKeyPath: '*.iconHref'
    },

    'ul li em': {
        textKeyPath: '*.title'
    }
}
</code></pre>

<p>Now all we need is a selector engine to hook this up to the nodes. It would be ideal if every browser supported <code>querySelectorAll</code>, but so far only Safari seems to have an implementation of <code>querySelectorAll</code><sup id="fnref:o"><a href="#fn:o" rel="footnote">1</a></sup> and FireFox 3 won&#8217;t include it, which boggles the mind a bit. Fortunately, Diego Perini has written an excellent selector engine called <a href="http://javascript.nwbox.com/NWMatcher/">NWMatcher</a> and has graciously permitted me to include it in Coherent. This gives me coverage for the vast majority of browsers that don&#8217;t support <code>querySelectorAll</code>. And Diego&#8217;s code is pretty fast too.</p>

<p>So now I&#8217;m thinking in terms of what the <em>right</em> API should be for this. I&#8217;m thinking something like the following:</p>

<pre><code>coherent.setupNodeWithSelectors($('outer'), {
    'ul': {
        contentKeyPath: 'links.arrangedContent'
    },

    'ul li img': {
         srcKeyPath: '*.iconHref'
    },

    'ul li em': {
        textKeyPath: '*.title'
    }
});
</code></pre>

<p>But imagine my surprise when I read about <a href="http://ejohn.org/blog/thoughts-on-queryselectorall/">the wacky behaviour of <code>querySelectorAll</code></a> this morning. This potentially explains some bugs I experienced the first time I tried to implement the selector API. I&#8217;m not entirely certain where I come down on the issue. But it sure <em>seems</em> that if you&#8217;re going to add a native feature to provide similar functionality to the numerous selector engines available, you should probably define the spec as closely as possible to the majority behaviour.</p>

<h3>Mimicking &#8220;standard&#8221; behaviour</h3>

<p>I think my best bet is to mimic the standard behaviour of the prevailing libraries. My initial solution is to prefix the selector with the ID of the scope node. So in the call above, the selectors translate as follows:</p>

<table style="margin: 20px auto;">
<tr><td style="text-align:right;padding-right:5px;">ul</td><td>&#x21D2;</td><td style="padding-left: 5px;">#outer ul</td></tr>
<tr><td style="text-align:right;padding-right:5px;">ul li img</td><td>&#x21D2;</td><td style="padding-left: 5px;">#outer ul li img</td></tr>
<tr><td style="text-align:right;padding-right:5px;">ul li em</td><td>&#x21D2;</td><td style="padding-left: 5px;">#outer ul li em</td></tr>
</table>

<p>Fortunately, both Safari&#8217;s implementation of <code>querySelectorAll</code> and Diego&#8217;s code allow the first part of the selector to match the node itself. This solves my problem until the W3C api guys decide to change the API. Then I&#8217;ll need to provide one behaviour for Safari 3.1 and another for future versions.</p>

<p>Joy.</p>

<p>On the other hand, this means that <code>PartList</code> will support selectors rather than the pseudo-selectors available in 1.0. I won&#8217;t say there have been numerous occasions where I&#8217;ve wished for this feature, but that&#8217;s only because I always had the option of tacking on a class to the target nodes. Now I won&#8217;t have to.</p>

<div class="footnotes">
<hr />
<ol>

<li id="fn:o">
<p>I&#8217;m sure someone will tell me that Opera supports <code>querySelectorAll</code>. And the truth is I could probably check in less time that it would take me to make fun of all three people who run Opera on a regular basis. But I&#8217;m still chuckling about how Andy compared Opera to the stinky kid in school who just wanted you to like him&#8230;&#160;<a href="#fnref:o" rev="footnote">&#8617;</a></p>
</li>

</ol>
</div>
<img src="http://coherentjs.org/wordpress/?ak_action=api_record_view&id=171&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://coherentjs.org/development/selectors-and-bindings/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Coherent 1.0 Release Candidate 1</title>
		<link>http://coherentjs.org/development/coherent-10-release-candidate-1/</link>
		<comments>http://coherentjs.org/development/coherent-10-release-candidate-1/#comments</comments>
		<pubDate>Fri, 25 Apr 2008 14:28:15 +0000</pubDate>
		<dc:creator>jeff</dc:creator>
				<category><![CDATA[Development]]></category>

		<guid isPermaLink="false">http://localhost:8888/?p=22</guid>
		<description><![CDATA[I&#8217;ve been working somewhat furiously to get Coherent ready for its first release. There&#8217;s already code in the wild on a heavy-traffic e-commerce site that is using it, but there is still a bit more testing I&#8217;d like to do. And the documentation could use another brush up.

If you&#8217;ve downloaded either the ZIP file or [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been working somewhat furiously to get Coherent ready for its first release. There&#8217;s already code in the wild on a heavy-traffic e-commerce site that is using it, but there is still a bit more testing I&#8217;d like to do. And the documentation could use another brush up.</p>

<p>If you&#8217;ve downloaded either the ZIP file or pulled down the SVN repository, you should probably update to get the latest bug fixes and other goodies.</p>
<img src="http://coherentjs.org/wordpress/?ak_action=api_record_view&id=170&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://coherentjs.org/development/coherent-10-release-candidate-1/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Properties And Bindings</title>
		<link>http://coherentjs.org/development/properties-and-bindings/</link>
		<comments>http://coherentjs.org/development/properties-and-bindings/#comments</comments>
		<pubDate>Wed, 05 Mar 2008 00:03:28 +0000</pubDate>
		<dc:creator>jeff</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Overview]]></category>

		<guid isPermaLink="false">http://localhost:8888/news/overview/properties-and-bindings</guid>
		<description><![CDATA[Possibly the two most important concepts in the Coherent library are properties and bindings. If you&#8217;re familiar with modern programming languages, you&#8217;ve probably run across properties before, but bindings may be new unless you&#8217;ve worked with Apple&#8217;s Cocoa library. In order to get the most out of Coherent, you&#8217;ll need to understand these two facilities.


Properties

In [...]]]></description>
			<content:encoded><![CDATA[<p>Possibly the two most important concepts in the Coherent library are properties and bindings. If you&#8217;re familiar with modern programming languages, you&#8217;ve probably run across properties before, but bindings may be new unless you&#8217;ve worked with Apple&#8217;s Cocoa library. In order to get the most out of Coherent, you&#8217;ll need to understand these two facilities.
<span id="more-169"></span></p>

<h3>Properties</h3>

<p>In object oriented programming, a property is any attribute of an object. Technically properties might be public or private, but principally, I usually think of properties as publicly accessible values. Any bit of code may query the value of a property or set its value.</p>

<p>Most modern object-oriented programming languages have some concept of properties. Some older languages like Java and C++ fake it via getter and setter methods. But some languages like Python, Ruby, and C# have native properties. JavaScript in Class A browsers<sup id="fnref:classA"><a href="#fn:classA" rel="footnote">1</a></sup> also supports properties using the following syntax:</p>

<pre><code>var someObject= {

    get foo()
    {
        return this.theValueOfFoo;
    },

    set foo(newFoo)
    {
        this.theValueOfFoo= newFoo;
    }

};
</code></pre>

<p>It&#8217;s not the ideal syntax, but it&#8217;s quite a bit better than the alternative:</p>

<pre><code>var someObject= {};
someObject.__defineGetter__('foo', function() {
    return this.theValueOfFoo;
});
someObject.__defineSetter__('foo', function(newFoo) {
    this.theValueOfFoo=newFoo;
});
</code></pre>

<p>You can then access this property directly and under the covers, JavaScript will call the correct methods.</p>

<pre><code>someObject.foo="I am Foo!";
window.alert(someObject.foo);
</code></pre>

<p>That&#8217;s all great so long as none of your visitors uses Internet Explorer. The barnacle encrusted JavaScript engine employed by Internet Explorer saw its last significant feature improvement nearly a decade ago. So it doesn&#8217;t have any of the shiny new features found in Class A browsers. It&#8217;s the killjoy of the browser community.</p>

<p>So unless you&#8217;re certain all your visitors have modern browsers, you&#8217;re stuck writing getter and setter methods like in Java or C++<sup id="fnref:objCstyle"><a href="#fn:objCstyle" rel="footnote">2</a></sup>. So the example above becomes:</p>

<pre><code>var someObject= {

    getFoo: function()
    {
        return this.theValueOfFoo;
    },

    setFoo: function(newFoo)
    {
        this.theValueOfFoo= newFoo;
    }

};
</code></pre>

<p>This may not seem like a big difference, but you&#8217;ll notice it when you go to use <code>someObject</code>:</p>

<pre><code>someObject.setFoo('I am Foo!');
window.alert(someObject.getFoo());
</code></pre>

<p>This may feel natural if you&#8217;re a C++ or Java programmer, but then you&#8217;re also probably accustomed to chewing broken glass, sticking needles in your eyes, and other painful party tricks.<sup id="fnref:cpp"><a href="#fn:cpp" rel="footnote">3</a></sup></p>

<h4>Observing properties</h4>

<p>One feature built into Coherent is the ability to observe the changes made to an object&#8217;s properties. For any KVO-compliant<sup id="fnref:kvoCompliant"><a href="#fn:kvoCompliant" rel="footnote">4</a></sup> object, you may add an observer via a call to:</p>

<pre><code>someObject.addObserverForKeyPath(observerObj, observerObj.observeFooChange,
                                 "foo");
</code></pre>

<p>Whenever the <code>foo</code> property of <code>someObject</code> changes, the <code>observeFooChange</code> method of <code>observerObj</code> will be called with the previous and new value. Exactly what <code>observerObj</code> chooses to do with the change information is up to you the developer.</p>

<p>For properties you implement via getter and setter methods, there&#8217;s nothing you need to do to notify observers that the property has changed. However, if your property is just a regular value on your object, you&#8217;ll need to use one of two methods to notify observers that the value has changed.</p>

<p>The first technique is to wrap modification of the property with calls to <code>willChangeValueForKey</code> and <code>didChangeValueForKey</code>. So to keep with the previous observer example, lets look at some code in <code>someObject</code> that updates the <code>foo</code> property:</p>

<pre><code>    addOneToFoo: function()
    {
        this.willChangeValueForKey('foo');
        ++this.foo;
        this.didChangeValueForKey('foo');
    },
</code></pre>

<p>This technique allows you to make numerous modifications to the <code>foo</code> property and only signal the observers when you&#8217;re good and ready. Additionally, you can use <code>willChange</code>/<code>didChange</code> to wrap calls to a number of methods which all trigger changes to the same property. These changes will be delayed and coalesced into a single update.</p>

<p>The second technique is to modify your properties by calling <code>setValueForKey</code> or <code>setValueForKeyPath</code>. This is a <em>pseudo</em>-atomic operation that updates the property value and notifies observers all at once. Of course, under the covers, <code>setValueForKey</code> calls <code>willChange</code> and <code>didChange</code> for you. The <code>addOneToFoo</code> method could then be written as:</p>

<pre><code>    addOneToFoo: function()
    {
        this.setValueForKey(this.foo+1, 'foo');
    },
</code></pre>

<p>Not substantially different, but if you call <code>setValueForKey</code> more than once, you (might) get more than one change notification.</p>

<h4>Coalesced property changes</h4>

<p>One of the important responsibilities of the <code>willChangeValueForKey</code> and <code>didChangeValueForKey</code> pair is to coalesce property changes. If you plan to call multiple methods that might trigger changes for a particular property, you can wrap those calls with a <code>willChange</code>/<code>didChange</code> pair. The change notification will only be triggered when the final <code>didChangeValueForKey</code> method is called.</p>

<p>Additionally, the first time <code>willChangeValueForKey</code> is called, it will retrieve the current value of the property. When the final <code>didChangeValueForKey</code> method is called, the change notification will only be triggered when the previous value and new value are different. This is important to keep the number of change notifications down to a manageable level.</p>

<p>Property change coalescing occurs no matter how you update your properties. So whether you call <code>setValueForKey</code>, <code>willChangeValueForKey</code>/<code>didChangeValueForKey</code>, or write your own getter/setter methods (e.g. <code>getFoo</code> and <code>setFoo</code>), if the <em>new</em> value isn&#8217;t any different than the existing value, no change notification will occur.</p>

<h3>Bindings</h3>

<p>At their most simple, bindings are a two way method of keeping objects synchronised without having to write an enormous amount of glue code. Through a binding, you are creating a mediated connection between a view or controller and your data model. Changes to one are reflected in the other automatically.</p>

<div class="figure">
<img src="http://localhost:8888/wp/wp-content/uploads/2008/03/binding1.png" alt="binding1.png" border="0" width="601" height="82" />
</div>

<p>This can be reflected in your UI with the following mark up:</p>

<pre><code>&lt;div class="inline-demo"&gt;
&lt;fieldset id="properties-bindings-demo1"&gt;
    &lt;label&gt;Name:&lt;/label&gt;
    &lt;div&gt;&lt;input type="text" valueKeyPath="person.name"
                nullPlaceholder="Your Name"&gt;&lt;/div&gt;
    &lt;label&gt;Greeting:&lt;/label&gt;
    &lt;div&gt;Hello, &lt;span textKeyPath="person.name"
                      nullPlaceholder="Your Name"&gt;&lt;/span&gt;.&lt;/div&gt;
&lt;/fieldset&gt;
&lt;/div&gt;

&lt;script&gt;
    coherent.DataModel('person', {name: 'Bozo the Clown'});
    coherent.setupNode($('properties-bindings-demo1'));
&lt;/script&gt;
</code></pre>

<p>And ultimately, this yields the following interaction:</p>

<p><style>
.inline-demo fieldset div
{
    line-height:24px;
    margin-left: 9em;
    margin-top: 3px;
}
.inline-demo fieldset div input
{
    margin-top:4px;
}
.inline-demo fieldset label
{
    float:left;
    clear:both;
    line-height: 24px;
    width: 8em;
    text-align: right;
}
.inline-demo .nullValue
{
    font-style: italic;
    color: #ccc;
}
</style></p>

<div class="inline-demo">
<fieldset id="properties-bindings-demo1">
    <label>Name:</label>
    <div><input type="text" valueKeyPath="person.name" nullPlaceholder="Your Name"></div>
    <label>Greeting:</label>
    <div>Hello, <span textKeyPath="person.name" nullPlaceholder="Your Name"></span>.</div>
</fieldset>
</div>

<script>
    coherent.DataModel('person', {name: 'Bozo the Clown'});
    coherent.setupNode($('properties-bindings-demo1'));
</script>

<p>As you modify the value in the input field, the values are pushed into your data model. First the <code>InputWidget</code> calls <code>setValueForKeyPath</code> to update the data model with the current value of the input field. The <code>Person</code> object triggers a change notification, which is observed by the <code>TextWidget</code>. The <code>TextWidget</code> updates its associated DOM node with the new value.</p>

<div class="figure"><img src="/wordpress/wp-content/uploads/2008/03/binding21.png" alt="binding2.png" border="0" width="601" height="133" /></div>

<h4>Bindings can be properties too</h4>

<p>It isn&#8217;t necessary to expose your bindings as properties, but it can be useful. For example, the <code>InputWidget</code> exposes a <code>value</code> binding, however, the <code>value</code> binding isn&#8217;t also exposed as a property: you can&#8217;t call <code>setValue</code> and <code>getValue</code> to retrieve the current widget value. On the other hand, the <code>ObjectController</code> exposes the <code>editable</code> binding and also has an <code>editable</code> property.</p>

<p>Typically, when a property is also exposed as a binding, setting the property should immediately set the binding. So, in the case of the <code>ObjectController</code>, setting the value of the <code>editable</code> property will automatically update the object at the other end of its <code>editable</code> binding.</p>

<h3>Wrapping it up</h3>

<p>An understanding of properties and bindings is essential to making effective use of Coherent. With luck, this overview has shed light on some of the essential details and given you confidence to dive in and write some code. It won&#8217;t hurt. I promise.</p>

<div class="footnotes">
<hr />
<ol>

<li id="fn:classA">
<p>Class A browsers include Safari and FireFox. Both of Opera&#8217;s users assure me it should be considered a Class A browser, and I&#8217;m certain they&#8217;re right. Microsoft Internet Explorer &mdash; if we&#8217;re charitable &mdash; is a class B browser.&#160;<a href="#fnref:classA" rev="footnote">&#8617;</a></p>
</li>

<li id="fn:objCstyle">
<p>You may also write your getter and setter methods using the Objective-C style. So you save three characters. Still, you wind up calling functions rather than accessing properties, so the purist cries.&#160;<a href="#fnref:objCstyle" rev="footnote">&#8617;</a></p>
</li>

<li id="fn:cpp">
<p>Just to be clear, I <em>am</em> a C++ programmer. So I know intimately the joy of being able to exclaim &#8220;Hey! I actually made the compiler do what I want!&#8221; after a marathon 36 hour session. And I&#8217;ve written enough Java to understand that its obsession with factories is nothing short of obscene.&#160;<a href="#fnref:cpp" rev="footnote">&#8617;</a></p>
</li>

<li id="fn:kvoCompliant">
<p>An object is KVO compliant if it is an instance of a class derived from <code>coherent.KVO</code> or has been adapted via a call to <code>coherent.KVO.adapt</code> or <code>coherent.KVO.adaptTree</code>. This means it has all the goodness Coherent has to offer.&#160;<a href="#fnref:kvoCompliant" rev="footnote">&#8617;</a></p>
</li>

</ol>
</div>
<img src="http://coherentjs.org/wordpress/?ak_action=api_record_view&id=169&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://coherentjs.org/development/properties-and-bindings/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Faster than a Locomotive?</title>
		<link>http://coherentjs.org/development/faster-than-a-locomotive/</link>
		<comments>http://coherentjs.org/development/faster-than-a-locomotive/#comments</comments>
		<pubDate>Mon, 25 Feb 2008 17:25:42 +0000</pubDate>
		<dc:creator>jeff</dc:creator>
				<category><![CDATA[Development]]></category>

		<guid isPermaLink="false">http://localhost:8888/news/development/faster-than-a-locomotive</guid>
		<description><![CDATA[After squashing a couple nasty bugs this weekend, I got to thinking about the performance implications of my solution. In a nutshell, the solution required wrapping getter methods with code to establish the ownership link between the value and the object. This wrapping only occurs for properties that are observed or part of a dependent [...]]]></description>
			<content:encoded><![CDATA[<p>After squashing a couple nasty bugs this weekend, I got to thinking about the performance implications of my solution. In a nutshell, the solution required wrapping getter methods with code to establish the ownership link between the value and the object. This wrapping only occurs for properties that are observed or part of a dependent key relationship, but still, we&#8217;re talking an extra layer of code.
<span id="more-168"></span></p>

<h3>It&#8217;s UI code</h3>

<p>Fundamentally, the purpose of Coherent is to make writing the UI of Web applications more like writing the UI of desktop applications. And when you really think about the top needs for UI code, blinding speed just isn&#8217;t one of them.</p>

<p>For high-level code, I&#8217;d much rather trade off a little bit of speed in favour of a more flexible, de-coupled implementation. For low-level code, like CSS Selector engines, you absolutely <em>must</em> have the fastest you can get. Until your browser supports the <a href="http://www.w3.org/TR/selectors-api/">W3C Selectors API</a>, like nightly WebKit builds, you want your JavaScript implementation to be as fast as possible. But for high-level APIs intended to speed application development, a few extra cycles lost here and there won&#8217;t hurt.</p>

<h3>Trade-offs</h3>

<p>One of the trade-offs that I&#8217;m making revolves around when to perform the method wrapping. If this were desktop software, the model objects might live a life partially independent of the UI. It&#8217;s conceivable your code might perform some sort of background processing and fill in your model objects. In that case, you don&#8217;t necessarily want to be calling wrapped methods, you want every last drop of processor power at your disposal. In that case, you&#8217;d only want to wrap methods when the object becomes the target of an observer.</p>

<p>But for Web applications, the presumption I&#8217;m making is that the data wouldn&#8217;t be on the client in the first place if it weren&#8217;t taking part in the UI. Therefore, let&#8217;s spend the minimum amount of time creating wrapped methods (they don&#8217;t grow on trees, you know) and most likely, once a property gets observed, the rest of the instances of that class are also likely to get observed as well.</p>

<p>So the trade off in this case is less time spent wrapping methods in exchange for a few more change notifications sent when no one cares.</p>

<h3>Writing the code for you</h3>

<p>It&#8217;s been suggested that Coherent could use a facility to automatically generate getter and setter methods. The syntax I&#8217;m thinking would be something like the following:</p>

<pre><code>var MyClass= Class.create(coherent.Bindable, {

    exposedBindings: ['content'],

    properties: ['name', 'description'],

    ...

});
</code></pre>

<p>If you leave out any implementation of the <code>content</code> binding Coherent would automatically generate the following:</p>

<pre><code>    ...

    observeContentChange: function(change, keyPath, context)
    {
        this.setContent(change.newValue);
    },

    setContent: function(newContent)
    {
        this.__content= newContent;
    },

    getContent: function()
    {
        return this.__content||null;
    },

    ...
</code></pre>

<p>And if you didn&#8217;t implement methods for the <code>name</code> and <code>description</code> properties, Coherent would generate the following methods to implement them:</p>

<pre><code>    ...

    setName: function(newName)
    {
        this.__name= newName;
    },

    getName: function()
    {
        return this.__name||null;
    },

    setDescription: function(newDescription)
    {
        this.__description= newDescription;
    },

    getDescription: function()
    {
        return this.__description||null;
    },

    ...
</code></pre>

<p>I&#8217;m not certain how valuable this really is. Is it that much better than calling <code>this.setValueForKey("Bob", "name")</code> when you need to set the object&#8217;s name? It would be a bit more clear, and I could generate the wrapped versions at the same time to reduce one layer of indirection.</p>

<p>There might be additional benefits to knowing in advance the list of properties a class exposes, but I don&#8217;t know whether limiting you to only the properties you declare is right in such a dynamic language as JavaScript. Still, it&#8217;s something to think about post 1.0.</p>
<img src="http://coherentjs.org/wordpress/?ak_action=api_record_view&id=168&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://coherentjs.org/development/faster-than-a-locomotive/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>New Tutorial on Writing Widgets</title>
		<link>http://coherentjs.org/development/new-tutorial-on-writing-widgets/</link>
		<comments>http://coherentjs.org/development/new-tutorial-on-writing-widgets/#comments</comments>
		<pubDate>Fri, 15 Feb 2008 05:36:14 +0000</pubDate>
		<dc:creator>jeff</dc:creator>
				<category><![CDATA[Development]]></category>

		<guid isPermaLink="false">http://nerd.metrocat.org/2008/02/new-tutorial-on-writing-widgets</guid>
		<description><![CDATA[As the release of Coherent looms nearer, I&#8217;ve been encouraged to start writing some documentation. My first effort is up: Writing a Widget. This tutorial takes you through creating a widget using Coherent starting with raw mark up and ending with a functional (if simple) widget. Thanks to some great feedback (and encouragement) from Neil [...]]]></description>
			<content:encoded><![CDATA[<p>As the release of Coherent looms nearer, I&#8217;ve been encouraged to start writing some documentation. My first effort is up: <a href="/2008/02/writing-a-widget">Writing a Widget</a>. This tutorial takes you through creating a widget using Coherent starting with raw mark up and ending with a functional (if simple) widget. Thanks to some great feedback (and encouragement) from <a href="http://neilmix.com">Neil Mix</a> of <a href="http://pandora.com">Pandora</a>, this tutorial doesn&#8217;t suck.</p>

<p>Oh, and if you haven&#8217;t tried Pandora yet, what the heck are you waiting for? This is one of the coolest things I&#8217;ve run across in ages. Of course, now my wallet is going to be completely empty because I&#8217;ve been turned onto a half dozen musicians I&#8217;d never heard of before&#8230;</p>
<img src="http://coherentjs.org/wordpress/?ak_action=api_record_view&id=167&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://coherentjs.org/development/new-tutorial-on-writing-widgets/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Writing a Widget</title>
		<link>http://coherentjs.org/tutorials/writing-a-widget/</link>
		<comments>http://coherentjs.org/tutorials/writing-a-widget/#comments</comments>
		<pubDate>Thu, 14 Feb 2008 06:50:47 +0000</pubDate>
		<dc:creator>jeff</dc:creator>
				<category><![CDATA[Tutorials]]></category>

		<guid isPermaLink="false">http://localhost:8888/news/tutorials/writing-a-widget</guid>
		<description><![CDATA[Coherent strives to present a sane Model View Controller paradigm for client-side Web development. So writing a Widget using the Coherent library may be a bit different from what your accustomed to. However, if you&#8217;ve ever written desktop software, this should feel right at home.

For this tutorial, we&#8217;re going to build a simple photo gallery [...]]]></description>
			<content:encoded><![CDATA[<p>Coherent strives to present a sane Model View Controller paradigm for client-side Web development. So writing a Widget using the Coherent library may be a bit different from what your accustomed to. However, if you&#8217;ve ever written desktop software, this should feel right at home.</p>

<p>For this tutorial, we&#8217;re going to build a simple photo gallery to display a static list of images with captions. In a future tutorial, we&#8217;ll see how we can expand this sample to pull image information from Flickr or other sources.
<span id="more-166"></span></p>

<p><link rel="stylesheet" href="http://localhost:8888/js/coherent/demo/widget/widget.css" media="screen"/></p>

<script src="http://localhost:8888/js/coherent/demo/widget/PhotoGallery.js"></script>

<p><a name="demo"></a></p>

<div id="photo-gallery" markdown="0">
    <img src="/js/coherent/demo/widget/photos/molly-1.jpg">
    <p>Caption</p>
    <a href="#" class="next">Next</a>
    <a href="#" class="prev">Previous</a>
</div>

<script markdown="0">
var galleryData= {
    selected: 0,
    photos: [
        {
            caption: "Molly on the slide.",
            href: "http://localhost:8888/js/coherent/demo/widget/photos/molly-1.jpg"
        },
        {
            caption: "Monkey in training",
            href: "http://localhost:8888/js/coherent/demo/widget/photos/molly-2.jpg"
        },
        {
            caption: "Spaz attack!",
            href: "http://localhost:8888/js/coherent/demo/widget/photos/molly-3.jpg"
        },
        {
            caption: "Ride `Em, Molly!",
            href: "http://localhost:8888/js/coherent/demo/widget/photos/molly-4.jpg"
        },
        {
            caption: "Don't mess with my zebra.",
            href: "http://localhost:8888/js/coherent/demo/widget/photos/molly-5.jpg"
        }
    ]
};
new PhotoGallery('photo-gallery', galleryData, {
                    images: '*.photos',
                    selectedIndex: '*.selected'
                 });
</script>

<p>The buttons at the bottom allow visitors to cycle forward and backwards through the list of available photos. In this case, wrapping around is not supported, but would be easy to implement.</p>

<p>Go ahead, try it. It just works.</p>

<h3>Parts is parts</h3>

<p>Obviously, our widget is nothing without some HTML to hook it up to. Let&#8217;s create the bare minimum of markup: we need an image to display the current photo, a paragraph to present the photo&#8217;s caption, and two links to serve as our next and previous button. We&#8217;ll rely on Safari&#8217;s top-notch CSS support to make it all look pretty.</p>

<pre><code>&lt;div id="photo-gallery"&gt;
    &lt;img src="photos/molly-1.jpg"&gt;
    &lt;p&gt;Caption&lt;/p&gt;
    &lt;a href="#" class="next"&gt;Next&lt;/a&gt;
    &lt;a href="#" class="prev"&gt;Previous&lt;/a&gt;
&lt;/div&gt;
</code></pre>

<p>That&#8217;s simple. Our markup maps to our widget through <code>Parts</code> (and <code>PartList</code>s not seen here). A <code>Part</code> is a lightweight stand in for a DOM node (often called a flyweight). All a <code>Part</code> contains is the ID of the DOM node, and if the node doesn&#8217;t have one, it will be assigned one. This alleviates a lot of headaches for the server side of things, because you don&#8217;t have to write code to generate unique IDs. In addition, because you won&#8217;t have DOM node references in your local variables, you reduce the risk of memory leaks in Internet Explorer when creating closures. To retrieve the DOM node, you simply invoke the <code>Part</code> as if it were a function (which it is) and if the node exists, you&#8217;ll get back a reference to it.</p>

<p>The real work happens in our widget&#8217;s <code>init</code> method. After initialising its <code>images</code> and <code>selectedIndex</code> properties to reasonable default values, the widget creates two widgets of its own. The first is an image widget and the second is a text widget. The first parameter to each constructor is the node that will be managed by the widget. The second and third parameters are the relative data source for the widget and a map describing where the widget can find its data; we&#8217;ll get to this in the section on <a href="#data-binding">Data Binding</a>.</p>

<p>We also add listeners for the click event on both the next and previous buttons. At the moment, Coherent depends on some methods having an API similar to the Prototype library, but expect this dependency to go away in the future.</p>

<pre><code>var PhotoGallery= Class.create(coherent.Widget, {

    ...

    init: function()
    {
        this.images= null;
        this.selectedIndex= -1;

        new coherent.ImageWidget(this.image(), this, {
                                    src: '*.selectedImage.href'
                                 });
        new coherent.TextWidget(this.caption(), this, {
                                    text: '*.selectedImage.caption'
                                });

        Event.observe(this.nextButton(), 'click',
                      this.nextButtonClicked.bindAsEventListener(this));
        Event.observe(this.prevButton(), 'click',
                      this.prevButtonClicked.bindAsEventListener(this));
    },

    image: Part('img'),
    caption: Part('p'),
    nextButton: Part('a.next'),
    prevButton: Part('a.prev'),

    ...

});
</code></pre>

<p>For widgets like our photo gallery, it really is this simple. As your widgets get more complex, of course, your <code>init</code> logic will get a bit more complex. But by using sub-widgets, <code>Part</code>s and <code>PartList</code>s, your work can be less onerous.</p>

<h3>Handling events</h3>

<p>At the moment, our photo gallery isn&#8217;t very interesting, but before we get into stuff that&#8217;s specific to the Coherent library, let&#8217;s implement the click event handlers to allow the visitor to switch between the available images.</p>

<p>The logic for both <code>nextButtonClicked</code> and <code>prevButtonClicked</code> is basically the same: stop the DOM event from invoking the anchor, return if there are no images or if we&#8217;re at the beginning or end of the list (for previous and next respectively), otherwise, update the <code>selectedIndex</code> property to reflect either the previous or next index. And finally, update the navigation controls.</p>

<p>Updating the navigation controls is similarly very simple: if we&#8217;re at the beginning of the list, add the <code>disabled</code> class to the previous link, otherwise remove it; and if we&#8217;re at the end of the list, add the <code>disabled</code> class to the next link, otherwise remove it. If there are no images at all, disable both buttons.</p>

<pre><code>var PhotoGallery= Class.create(coherent.Widget, {
    ...

    nextButtonClicked: function(event)
    {
        Event.stop(event);
        if (!this.images)
            return;

        var newIndex= this.selectedIndex+1;
        if (newIndex&gt;=this.images.length)
            return;

        this.setValueForKey(newIndex, 'selectedIndex');
        this.updateNavigation();
    },

    prevButtonClicked: function(event)
    {
        Event.stop(event);
        if (!this.images)
            return;

        var newIndex= this.selectedIndex-1;
        if (newIndex&lt;0)
            return;

        this.setValueForKey(newIndex, 'selectedIndex');
        this.updateNavigation();
    }

    updateNavigation: function()
    {
        if (!this.images || !this.selectedIndex)
            Element.addClassName(this.prevButton(), 'disabled');
        else
            Element.removeClassName(this.prevButton(), 'disabled');

        if (!this.images || this.selectedIndex+1&gt;=this.images.length)
            Element.addClassName(this.nextButton(), 'disabled');
        else
            Element.removeClassName(this.nextButton(), 'disabled');
    },

    ...
});
</code></pre>

<p>That&#8217;s it. Again, this is a pretty simple widget, but you&#8217;ll find that using <code>Part</code>s and sub-widgets makes your event handlers considerably simpler.</p>

<h3>Widget Properties</h3>

<p>In the previous code fragment, you may have noticed two calls to an unfamiliar method: <code>setValueForKey</code>. This method is declared on the <code>coherent.KVO</code> class which is an ancestor of <code>coherent.Widget</code>. Essentially, calling <code>setValueForKey(newValue, keyName)</code> is equivalent to the following code:</p>

<pre><code>this.willChangeValueForKey(keyName);
this[keyName]= newValue;
this.didChangeValueForKey(keyName);
</code></pre>

<p>Of course, <em>that</em> clears things up, doesn&#8217;t it? The call to <code>willChangeValueForKey</code> lets observers know that you intend to change the value of a particular property. After you change it, calling <code>didChangeValueForKey</code> alerts observers that the value has actually changed. Under the covers, <code>didChangeValueForKey</code> will check to make certain that the value actually <em>has</em> changed before invoking the observers&#8217; change notification handlers. Calling <code>setValueForKey</code> does this for you.</p>

<p>Now you might be wondering whether you need to add calls to <code>willChangeValueForKey</code> and <code>didChangeValueForKey</code> to all your setter methods. Good news! The answer is no. Coherent will automatically wrap your setter with calls to <code>willChangeâ€¦</code> and <code>didChangeâ€¦</code> so you don&#8217;t need to worry about it.<sup id="fnref:1"><a href="#fn:1" rel="footnote">1</a></sup></p>

<p>In addition to the list of images and the index of the selected image, our photo gallery widget needs a property to reflect the selected image itself. We&#8217;ll define an accessor method, because its value is computed rather than set.<sup id="fnref:2"><a href="#fn:2" rel="footnote">2</a></sup> The method checks first to make certain the <code>images</code> property has a value and that an image is actually selected, returning <code>null</code> if either condition is false. Otherwise, it returns the object in the <code>images</code> array at the index determined by <code>selectedIndex</code>.</p>

<p>Next we need to determine how the properties interact. In this case, the <code>selectedImage</code> property is dependent on the value of <code>selectedIndex</code> and <code>images</code>. So we declare this dependency relationship in <code>keyDependencies</code> &mdash; a special property you can add to your class definition and is processed via the <code>__subclassCreated</code> method of the Widget class. Each entry in the <code>keyDependencies</code> map is the name of a property and its value is an array of other properties upon which the property value depends.</p>

<pre><code>var PhotoGallery= Class.create(coherent.Widget, {
    ...

    getSelectedImage: function()
    {
        if (!this.images || -1===this.selectedIndex)
            return null;
        return this.images[this.selectedIndex];
    },

    keyDependencies: {
        'selectedImage': ['selectedIndex', 'images']
    },

    ...
});
</code></pre>

<p>Normally, widgets will have considerably more properties than our photo gallery, but each property will be implemented roughly like <code>selectedImage</code>.</p>

<h3 id="data-binding">Data Binding</h3>

<p>Most widgets need to interact with the data from your application. (If not, what the heck do they do?) Widgets need to declare these data connection points, called bindings, so that Coherent can manage notifying the widget when a bound value changes. Widgets can also push changes out to the bound data as well, and Coherent will notify the owner of the data via a change notification.</p>

<p>There are two places that Widgets can look to resolve their bindings: in the global data model and in their relative data source (parameter #2 to the constructor). In the <code>init</code> method, we encountered two bindings: the <code>src</code> for the <code>ImageWidget</code> and the <code>text</code> for the <code>TextWidget</code>. The third argument to the constructors specifies a map in which the keys are the names of the widget&#8217;s exposed bindings and the values are paths to where the widgets should look for their data. Paths that begin with <code>*</code> are assumed to be relative to the data source provided as parameter #2 to the constructor. Other paths are to objects that live in the global data model, which we&#8217;ll explore in a future tutorial.</p>

<p>For our photo gallery, the first step is to define the external data our widget is expecting. In order for our widget to respond to changes to the external data, we must define observer methods for each exposed binding. Coherent will automatically call our widget&#8217;s observer method when external data changes.</p>

<p>We&#8217;ll expose bindings for the list of images and the index of the selected image. Because this is such a simple example, when these values change in the data model, we&#8217;ll just update a local property with the new value.</p>

<pre><code>var PhotoGallery= Class.create(coherent.Widget, {
    ...

    exposedBindings: ['images', 'selectedIndex'],

    observeImagesChange: function(change, keyPath, context)
    {
        if (coherent.ChangeType.setting!==change.changeType)
            return;

        this.setValueForKey(change.newValue, 'images');
        this.updateNavigation();
    },

    observeSelectedIndexChange: function(change, keyPath, context)
    {
        this.setValueForKey(change.newValue, 'selectedIndex');
        this.updateNavigation();
    },

    ...
});
</code></pre>

<p>Through the magic occurring behind the scenes, these two observer methods will cause a change notification for the photo gallery&#8217;s <code>selectedImage</code> property, which in turn will generate change notifications for the <code>src</code> and <code>text</code> bindings of the image widget and text widget. Your UI will update automatically.</p>

<p>In most cases, your observer methods will not usually be this simple. However, you can often factor out some logic like the call to the method <code>updateNavigation</code> &mdash; which enables and disables the next and previous buttons.</p>

<h3>Create the Widget</h3>

<p>The data for our photo gallery could come from any where, but for now, we&#8217;ll just hard-code some photos and captions into our HTML document. Our <code>galleryData</code> structure contains an entry for the index of the selected photo as well as an array of photos. These don&#8217;t have to both be in the same place, in fact, a future tutorial will demonstrate using an <code>ArrayController</code> to manage the selection and an <code>AjaxController</code> to fetch the photos from Flickr.</p>

<pre><code>var galleryData= {
    selected: 0,
    photos: [
        {
            caption: "Molly on the slide.",
            href: "photos/molly-1.jpg"
        },
        {
            caption: "Monkey in training",
            href: "photos/molly-2.jpg"
        },
        {
            caption: "Spaz attack!",
            href: "photos/molly-3.jpg"
        },
        {
            caption: "Ride `Em, Molly!",
            href: "photos/molly-4.jpg"
        },
        {
            caption: "Don't mess with my zebra.",
            href: "photos/molly-5.jpg"
        }
    ]
};
</code></pre>

<p>Now that we have data, we can create our widget. All that&#8217;s needed is to instantiate a <code>PhotoGallery</code> object. Just like when we created the <code>ImageWidget</code> and <code>TextWidget</code>, we pass the DOM node for the widget (as an ID this time), the object that will be the source of the widget&#8217;s data, and a map indicating how the exposed bindings hook up to the data source.</p>

<pre><code>new PhotoGallery('photo-gallery', galleryData, {
                    images: '*.photos',
                    selectedIndex: '*.selected'
                 });
</code></pre>

<h3>See it in action</h3>

<p>If this sounds simple, it really is. In case you didn&#8217;t notice, the <a href="#demo">photo gallery</a> at the top of the page was live. And if you&#8217;d like to see how it works, why not <a href="http://localhost:8888/download/">download the source</a> and check it out?</p>

<p>The next tutorial (stay tuned) will cover having multiple widgets accessing the same data model. I&#8217;m thinking of having the same simple photo gallery, but adding widgets to allow managing the list of photos.</p>

<div class="footnotes">
<hr />
<ol>

<li id="fn:1">
<p>And if you&#8217;re only targeting class A browsers, you don&#8217;t even have to call <code>setValueForKey</code> or <code>willChange&amp;hellip;</code>/<code>didChange&amp;hellip;</code> because Coherent will automatically wrap your properties with getter and setter methods that make the calls for you. Just one more reason to long for Internet Explorer 8.&#160;<a href="#fnref:1" rev="footnote">&#8617;</a></p>
</li>

<li id="fn:2">
<p>Accessor methods can either use the Java-esque style of <code>get</code> and <code>set</code> followed by the capitalised name of the property or the Objective-C style where the getter method is named the same as the property and the setter is named with <code>set</code> followed by the capitalised name of the property. Use whichever style is most comfortable for you.&#160;<a href="#fnref:2" rev="footnote">&#8617;</a></p>
</li>

</ol>
</div>
<img src="http://coherentjs.org/wordpress/?ak_action=api_record_view&id=166&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://coherentjs.org/tutorials/writing-a-widget/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
