There was a comment on IEclipseContext less code Rene asked how the publishing into parent contexts is done.
IEclipseContext provides 2 ways to publish information:
- IEclipseContext#set
- IEclipseContext#modify
I think 99% of the people are using IEclipseContext#set
because they could make up what IEclipseContext#modify
is good for.
The problem with IEclipseContext#set
is that pushes the value in the context you have called it on, if you want to publish a value somewhere in the parent hiearchy you have to search the IEclipseContext hierarchy yourself == you need to know exactly how the thing working and in which parent-context the original creator of the expected the value to reside.
So you often see code like this:
@Inject IEclipseContext context; public void publish() { TableViewer v = ...; v.addSelectionChangeListener( ... { context.getParent().set(Person.class, p) } ); }
for e4 parts the context you are publishing to is the PerspectiveContext
or if there are no perspectives the WindowContext
. Let’s suppose you have perspectives and now your requirements change and the value has to be published to WindowContext
.
To break up this tight coupling between the publisher and publishing target you can make use of IEclipseContext#modify
. Instead of publishing the value into the context instance the method is called on it search the parent hierarchy for the matching slot.
To know in which slot it publishes one has to call declare the variable on the context using IEclipseContext#declareModifiable
.
If you are in a e4 application you don’t have to make this call. Haven’t you ever wondered about MContext#variables: List<String>
. Congrats you’ve just learned how to define variables in contexts created by the e4 framework – no matter if you are using SWT or JavaFX as a rendering technology.
This makes the original code look like:
@Inject IEclipseContext context; public void publish() { TableViewer v = ...; v.addSelectionChangeListener( ... { context.modify(Person.class, p) } ); }
or if you want to remove the IEclipseContext
@Inject @ContextValue(contextKey="my.Person") ContextBoundValue<Person> value; public void publish() { TableViewer v = ...; v.addSelectionChangeListener( ... { value.publish(p) } ); }
What is this @ContextValue annotation. Is this a standard e4 annotation?
Ah, got it, your described that in https://tomsondev.bestsolution.at/2013/11/21/writing-ieclipsecontext-less-code/