I’ve recently been asked how to deal with touch events in DukeScript. One option is
to use hammer.js, a JavaScript Library that supports
the most important number of events and gestures. You could create an API for that and wrap
the events in Java Events, but it’s much more elegant to stay in the knockout world.
We don’t need to pollute our viewmodels with the notion of events, we can still use declarative
bindings by simply registering knockout bindings for the hammer events. I used knockout-hammer
as starting point, but I had to modify it a bit to get it to work:
Now all we need to do is to make sure the two javascript libraries are loaded in the
correct order. I created two classes for that. These classes are in the javascript libraries
module of my DukeScript project (because the POM of this module has some special
settings for handling JavaScript). Both classes use the @JavaScriptRessource Annotation to register
the JavaScript libraries:
When calling KnockoutHammer.init(), HammerLibrary.init() is
called first, so this JavaScript file is loaded before the bindings. Now we can use our library in a project:
In index.html:
The actual event is prefixed with “hm”, so it’s “hmTap”. The name of the handler function is “onHmTap”.
We can also pass some constraints. In our case we collect all the taps that happen in a 500ms interval.
Now let’s have a look at the function that is called on our viewmodel:
DukeScript recognizes the “tapCount” property of the method signature and automatically extracts the matching value from the event.
Now launch the application on your Android or iOS device and check the result.
If successful I suggest doing a little victory dance to this tune.