Domanda

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() /*-{
        $wnd.myWidget.@de.jsni.test.client.MyComponent::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?

È stato utile?

Soluzione 2

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.

Altri suggerimenti

The problem you have is when a MyComponent is created, $wnd.myWidget is set to refer to that item. So, if you create MyComponent #1, then MyComponent #2, you will always have $wnd.myWidget that equals MyComponent #2.

Rather than defining a method which sets a JS variable, refer to the window directly in the native method, as follows:

public native void myonclick(MyComponent comp) /*-{
    comp.@de.jsni.test.client.MyComponent::doSomething()();
}-*/;

Then, in the click handler, call myonclick as follows:

@Override
public void onClick(ClickEvent event) {
     myonclick(MyComponent.this);
}

I think this should work. Let me know if there are any issues, I'll try to help.

update: You could try the following, but honestly, I don't know if it will play well with external javascript. I've never really had to work through this use case.

public native void myonclick() /*-{
    this.@de.jsni.test.client.MyComponent::doSomething()();
}-*/;
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top