Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace element with my GWT widget?

Tags:

widget

gwt

Is it possible to replace known html element with my widget component? (Emphasis on the word 'replace', I don't want to put the widget in that element. :)

<body>
  <img />
  <div />
  <a id="tmpEl" />
  ...
  <img />
</body>

would become

<body>
  <img />
  <div />
  <div class="gwt-panel">...</div>
  ...
  <img />
</body>

I tried something like this...

tmpEl.getParentElement().replaceChild(myPanel.getElement(), tmpEl);

...but the resulting DOM elements were 'deaf', i.e. they did not receive click events. (To make this work I would probably have to call RootPanel.get().adopt(widget), but that method is not accessible.)

For a second I thought HTMLPanel.addAndReplaceElement could be the answer, but that only works when your 'placeholder' element is (direct) child of HTMLPanel widget. Which is obviously not my case. :(

Note please that I only know id of that element, I'm not creating it. Simply put: I need exactly what the question says.

As for 'DOM manipulation at higher level': I will happily manipulate the DOM at highest possible level if it lets me place widget instead of that placeholder element.

like image 772
Jaroslav Záruba Avatar asked Jun 19 '10 13:06

Jaroslav Záruba


2 Answers

It seems that calling widget.onAttach() after inserting widget into DOM does the trick.

class MyWidget extends Composite
{
  ...

  public void attach()
  {
    /* Widget.onAttach() is protected
     */
    onAttach();

    /* mandatory for all widgets without parent widget
     */
    RootPanel.detachOnWindowClose(this);
  }
}

tmpEl.getParentElement().replaceChild(myWidget.getElement(), tmpEl);
myWidget.attach();

Credit goes to André at Google Web Toolkit group.

I still wonder though why there is no RootPanel.addAndReplaceElement(Widget, Element), similar to HTMLPanel.addAndReplaceElement(Widget, Element).

like image 156
Jaroslav Záruba Avatar answered Sep 19 '22 07:09

Jaroslav Záruba


The solution is probably not so much different from what Igor suggested. I'd write something like this:

RootPanel rootPanel = RootPanel.get();
Element anchorElement = DOM.getElementById("tmpEl");
Anchor anchor = Anchor.wrap(anchorElement);

rootPanel.remove(anchor);
rootPanel.insert(new HTML("<div class='gwt-panel'>...</div>", 0); 
like image 42
Chris Lercher Avatar answered Sep 20 '22 07:09

Chris Lercher