dragome/dragome-sdk

Adding event listeners

Closed this issue · 6 comments

I'm unsure how to properly access Document instance and add events to it. (This is what GWT LibGDX backend seems to be doing a lot - in GwtInput, for example.) I really wish you added similar wrapper with static getter as you did with com.dragome.web.html.dom.Window - Window is super easy to access and modify with Window.getInstance(), while Document... yeah, not so much. org.w3c.dom.Document seems to be missing event listeners registration and I'm yet to find a way of accessing its instance without native code.

I'm not certain how to add event listeners to HTMLCanvasElement without native code. Should I just use a native method or is there a way I could create the event listeners fully in Java? I'm not a huge fan of JSNI, strongly typed code is much easier to maintain.

Event listener registration in org.w3c.dom.Document or any other target listener is not straightforward because of JDK org.w3c.dom interfaces definitions. In JDK, org.w3c.dom.Node does not extend EventTarget interface, and the way to add listeners within this model is to cast nodes to EventTarget and call addEventListener method, like this:

        Element button= document.getElementById("button");
        EventTarget eventTarget= JsCast.castTo(button, EventTarget.class);

        eventTarget.addEventListener("click", new EventListener()
        {
            public void handleEvent(Event event)
            {
                           ....
            }
        }, false);

Current way to obtain Document is using:

WebServiceLocator.getInstance().getDomHandler().getDocument()

You can also use:

Document document= ScriptHelper.evalCasting("document", Document.class, this);

Using JDK 8 we could create a static method inside Window or Document interfaces (or extension interfaces) to return a reference to Document with evalCasting approach.

Now that annotations are working on client side we could use dependency injection approach to get a cleaner code. It requires some tests over simple DI implementations, meanwhile I suggest to create a static method in some helper class to access Document more nicely.

Well, I'd appreciate any static method (or DI-based option) that you can use without 3 method calls like WebServiceLocator.getInstance().getDomHandler().getDocument() - to be honest, current approach is too well hidden for such a basic functionality as accessing document.

I've already added getDocument method to Window class.