Rolling out your own observables for eclipse DataBinding

04Dec07

Eclipse databinding lets you bind any two * Observables* to each other . You get out of box support to bind swt widgets and javabeans via the factories SWTObservables and BeanObservables .

But its real easy to roll out your own Observable if it doesn’t fall into the above two categories .

Lets say you want to bind an xml element text to a SWT text , we will need an observable for the xml element text .

xmlbinding

The code below extends AbstractObservableValue and everything is pretty straigtforward.

Since we do not expect asynchronous changes we may ignore staleness of observable objects.

Also, We need to observe the xml element for changes and fire valueChange with the diff on a change .

public class XmlElementAttributeObservableValue extends AbstractObservableValue{
 	Element element;
 	String propertyName;
 	public XmlElementAttributeObservableValue( Element element, final String propertyName) {
 		this.element = element;
 		this.propertyName = propertyName;
 		addListner(this.element, this.propertyName);
 	}

		private void addListner(final Element element, final String propertyName) {
 		ElementImpl elementImpl = (ElementImpl) element;
 		elementImpl.addEventListener("DOMAttrModified", new EventListener(){

				public void handleEvent(Event evt) {
 				final MutationEvent mutEvent = (MutationEvent) evt;
 				 if( mutEvent.getAttrName().equals(propertyName)){
 					 fireValueChange(new ValueDiff(){

							@Override
 						public Object getNewValue() {
 							return mutEvent.getNewValue();
 						}
 						@Override
 						public Object getOldValue() {
 							return mutEvent.getPrevValue();
 						}

						 });
 				 }
 			}

			}, false);
 	}

		public Object getValueType() {
 		return String.class;
 	}
 	public boolean isStale() {
 		return false;
 	}
 	@Override
 	protected Object doGetValue() {
 		return element.getAttribute(propertyName);
 	}
 	@Override
 	protected void doSetValue(Object value) {
 		element.setAttribute(propertyName, (String) value);
 	}
 }

Now binding xml text to swt text is really simple…

bindingContext.bindValue(SWTObservables.observeText(name,
								SWT.Modify),XmlObservables.observeElementText(element),
								null, null);
Advertisements


No Responses Yet to “Rolling out your own observables for eclipse DataBinding”

  1. Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: