Sauleil
Sauleil

Reputation: 2603

How to globally modify/access widget in GWT?

I just started yesterday using GWT, so maybe I'm not using the proper mechanism to solve that problem. So, I will try to explain exactly what I'm trying to do (with a simple problem) and 2 solutions I came up with to address that problem.

Problem:

Remember an index that can be updated via other widgets. Let's use focus to represent it.

[button 1]
[button 2]     [button A]
[button 3]

What we want to do is save or set the focus index when pressing right.

Solution 1: Global variables

I'm not usually fond of global variables, but in some case it's handy. By using, for instance, a dictionary (Dictionary.getDictionary) defined globally in the javascript, I could save the current index in it using the "Focus Event" in that case.

So, in the key press event, when left would be fired, I would just read the value in the dictionary.

I haven't tested yet, but I think it should work.

Solution 2: Set the value with the Element

Element element = DOM.getElementById("button id A");
element.<setFocusLeftKey>("button id [1..3]");

Here what I would like to achieve is just in the "onFocus" Event, I would simply set the value of that button.


So, any thought or solutions?

Thanks in advance.

P.S. I haven't found a better title for that, so if any suggestion, just put it in the comments and I'll update it.

Upvotes: 3

Views: 343

Answers (1)

Philippe Beaudoin
Philippe Beaudoin

Reputation: 3310

Using ID is definitely not the suggested way to do this in GWT. You say you need this mechanism to keep your views orthogonal to one another. This is noble, but in GWT you would achieve by using another resource (an EventBus, implemented in SimpleEventBus) that hides the different components from one another. In fact, I would argue that looking up the element by ID strongly couples the two views and is smelly.

Armed your EventBus you simply create and fire custom events that let the views (or, better, their presenters) communcate with one another. For example here you could have: NavigateRightFromButtonsEvent and NavigagteLeftFromButtonA event.

However, depending on the size of your app (or as a first experiment) you could decide to couple your two views. In this case simply pass the view for the button list into the one for button A and vice-versa. This is not really worse than relying on a global ID.

No matter which mechanism you choose (event bus or wiring the views together), you should now have access directly to the instance of the widget you want to highlight. To focus, just call setFocus(true) on it.

Upvotes: 1

Related Questions