Skip to content

Javascript Integration

Thiago Santos edited this page Aug 18, 2024 · 2 revisions

Important

This module is a case of studies that shows how you can extend Kotlin Routing to your context.

Maybe you need a routing system to provide HTML DOM elements in a WEB application.

sourceSets {
    jsMain.dependencies {
        implementation("dev.programadorthi.routing:javascript:$version")
    }
}

Setup the application

To get DOM Element based on routing you need to render based in the Routing instance.

import dev.programadorthi.routing.javascript.render
// ...

val router = routing {
    // ...
}

fun main() {
    render(
        routing = router,
        root = document.getElementById("root") ?: document.create.div(),
        initial = document.create.h1 {
            +"I am the initial content"
        }
    )
}

Define javascript handlers

import dev.programadorthi.routing.javascript.jsRoute
// ...

val router = routing {
    jsRoute(path = "/page1") {
        // return a HTML element
    }
}

Push an Element

router.call(uri = "...")

// or
import dev.programadorthi.routing.javascript.push
// ...
router.push(path = "...")

// or by name
import dev.programadorthi.routing.javascript.pushNamed
// ...
router.pushNamed(name = "...")

Replacing an Element

import dev.programadorthi.routing.javascript.replace
// ...
router.replace(path = "...")

// or by name
import dev.programadorthi.routing.javascript.replaceNamed
// ...
router.replaceNamed(name = "...")

Replacing all Elements

import dev.programadorthi.routing.javascript.replaceAll
// ...
router.replaceAll(path = "...")

// or by name
import dev.programadorthi.routing.javascript.replaceAllNamed
// ...
router.replaceAllNamed(name = "...")

Pop an Element

import dev.programadorthi.routing.javascript.pop
// ...
router.pop()

Neglect a route

Sometimes you need to navigate to a route but avoid put it on the stack and avoid a back navigation.

router.push(..., neglect = true)