Search code examples
javajavascriptgwtnamespacesjsni

GWT JSNI - Call java method of specific object


Consider the following widget. I add two of them to my page. The first one gets the name "widget1", the second one the name "widget2". It just should give out its own name, but called from javascript. (The example makes no sense, but is just a simple example to figure out, how it could be done.)

public class MyComponent extends Composite{

    String name;
    public MyComponent(String name) {
        this.name =name;

        Button b = new Button(name);
        b.addClickHandler(new ClickHandler() {

            @Override
            public void onClick(ClickEvent event) {
                myonclick();

            }
        });
        initWidget(b);
        declareMethod(this);
    }

    public native void declareMethod(MyComponent myWidget) /*-{
            $wnd.myWidget = myWidget;

    }-*/;

    public native void myonclick() /*-{
        [email protected]::doSomething()();
    }-*/;

    public void doSomething() {
        Window.alert(name);
    }
}

My problem now is: Both button alert the message "widget2". That's because I override the "myWidget"-variable in the "declareMethod". How can I archieve to call the doSomething()-method of the correct object? Can I use some kind of namespacing approach here?


Solution

  • I was solving my problem now by sinking the events i'm interested in e.g.: sinkEvents(Event) in the constructor and handling them in my onBrowserEvent(Event e) method. This was a mich more easy and convinient way for my problem.