B4J Question How To Honor DRY for Exit-by-Escape-key Functionality

cklester

Well-Known Member
Licensed User
I'm violating DRY by using this code in every single B4XPage class:

Code: Copy
Public Sub AddEscapeExit(ctl As Object)
    'allow Escape key to exit signin screen
    Dim r As Reflector
    r.Target = ctl
    r.AddEventFilter("keypressed","javafx.scene.input.KeyEvent.KEY_PRESSED")
End Sub

Sub KeyPressed_Filter (e As Event)
    Dim jo As JavaObject = e
    Dim keycode As String = jo.RunMethod("getCode", Null)
    If keycode = "ESCAPE" Then
        B4XPages.ClosePage(Me)
        e.Consume
    End If
End Sub

Everybody knows that violating DRY is a code-smell, so I'm asking, how do I generalize this algorithm so I can call it like this from every B4XPage class:

Code: Copy
Sub Main
    ...
    App.AddEscapeExit( myControl )
    ...
End Sub

In App.bas:

Code: Copy
Public Sub AddEscapeExit(ctl As Object)
    'allow Escape key to exit signin screen
    Dim r As Reflector
    r.Target = ctl
    r.AddEventFilter("keypressed","javafx.scene.input.KeyEvent.KEY_PRESSED")
End Sub

Sub KeyPressed_Filter (e As Event)
    Dim jo As JavaObject = e
    Dim keycode As String = jo.RunMethod("getCode", Null)
    If keycode = "ESCAPE" Then
        B4XPages.ClosePage(Me)
        e.Consume
    End If
End Sub

...but this does not work, probably because of the "B4XPages.ClosePage(Me)," as "Me" isn't accurate in the App class.

What do I do to generalize this functionality? Or should I bother? I have less than 10 pages, but if I ever want to upgrade the key event processing...

Maybe Event has the info I need. I'll check. But if anybody has an idea, please let me know.
 
Back
Top