Sunday, November 20, 2005

Observing field changes using Backbase

In a web application I'm writing I want to have fields on the page updated when the user changes other fields. This should happen client side or server side if server data is needed. Using Backbase this turns out to be quite easy.

There is an event called 'change' that is fired when the data in a field is changed and the user exits the field. When the change event is fired I can then perform some actions.

The other option is to 'observe' another element. When an element is observed, the observer also receives events that the observed item has. The event received by the observer is called 'observe-X', where 'X' is the name of the event fired by the observed item. If A has the 'change' event and B is observing A, then B will receive the 'observe-change' event. There is a limitation in that an observer can only observe one thing.

I wrote a simple demonstation of this, form3.html. This displays two input fields. When a number is entered into either field, and that field is exited, the sum of the two numbers is immediately displayed below then.

My first thought was to have the 'sum' element observe the two input fields and display the result when either of the two change. Unfortunately you can't observe two fields in the current version of Backbase so instead each field process its own 'change' event and sets 'sum' when it changes.

The 'sum' itself is just a span:
<span id="result">0</span>

The 'input' fields have an event handler:
<input id="number1" type="text" size="20" value="0">
<s:event b:on="change">
<s:task b:action="set"
b:target="id('result')/text()"
b:value="{(id('number1')/@value)+(id('number2')/@value)}"/>
</s:event>
</input>

The handler is for the 'change' event. When this occurs we use the 'set' action to set the value of a DOM node. The 'target' and 'value' of the 'set' action is defined using XPath. For the value I take the 'value' attribute of the number1 and number2 nodes. These are input fields, where 'value' holds the data in the field. The target is the 'result' span, choosing to replace the text of that span.

The same code exists for the 'number2' input field. Any event could be run during the 'change' handler. I could have done an Ajax request to the server to do the calculation for example.

Categories:

0 Comments:

Post a Comment

<< Home