Kotlin for JavaScript

Knockout.js Examples

Knockout is an interesting JavaScript library that helps to build an interactive HTML5 and CSS applications. Knockout is comparable to React and Vue.

Source code at GitHub https://github.com/ibinti/ko4knockout 

settings.gradle.kts

pluginManagement {
    resolutionStrategy {
        eachPlugin {
            if (requested.id.id == "kotlin2js") {
                useModule("org.jetbrains.kotlin:kotlin-gradle-plugin:${requested.version}")
            }
            if (requested.id.id == "kotlin-dce-js") {
                useModule("org.jetbrains.kotlin:kotlin-gradle-plugin:${requested.version}")
            }
        }
    }
}

build.gradle.kts

import org.jetbrains.kotlin.gradle.tasks.Kotlin2JsCompile

plugins {
    id("kotlin2js") version "1.3.11"
    id("kotlin-dce-js") version "1.3.11"
}

dependencies {
    implementation(kotlin("stdlib-js"))
}

repositories {
    jcenter()
}

defaultTasks("uglifyjs")

tasks {
    register<Exec>("uglifyjs") {
        dependsOn("runDceKotlinJs")
        /*
        uglifyjs is installed on the system with npm 
        */
        commandLine("uglifyjs", "build/kotlin-js-min/main/kotlin.js", "build/kotlin-js-min/main/koko.js", "-c","-m", "-o", "build/kotlin-js-min/main/koko.min.js")
    }
    compileKotlin2Js {
        kotlinOptions {
            outputFile = "${sourceSets.main.get().output.resourcesDir}/koko.js"
            moduleKind = "plain"
            sourceMap = false
            sourceMapEmbedSources = "never"
            metaInfo = false
        }
    }
}

Main.kt

package okoko
import kotlin.browser.document
import kotlin.browser.window
external fun jQuery(selector: dynamic): dynamic = definedExternally

fun log() {
    println("log from Kotlin for JavaScript!")
}

fun jtext(selector:dynamic,txt:dynamic) {
    jQuery(selector).text(txt)
}

fun index() {
    jQuery("p").click( {
        jtext("p","Thank You, Sir!") 
        log()
    })
    jtext("p","If you click on me, you will be mesmerized.")
}

fun helloworld() {
    js("""
// This is just a copy and paste of knockout.js hello world example 
// from knockoutjs. (https://knockoutjs.com/examples/helloWorld.html)
var ViewModel = function(first, last) {
    this.firstName = ko.observable(first);
    this.lastName = ko.observable(last);
 
    this.fullName = ko.pureComputed(function() {
        // Knockout tracks dependencies automatically. It knows that fullName depends on firstName and lastName, because these get called when evaluating fullName.
        return this.firstName() + " " + this.lastName();
    }, this);
};
 
ko.applyBindings(new ViewModel("Planet", "Earth")); // This makes Knockout get to work
    """)
}

fun boombayah() {
    jQuery(document).ready({
        val title = jQuery("title").text()
        when(title) {
            "index.html" -> index()
            "helloworld.html" -> helloworld()
            "helloworld2.html" -> helloworld2()
            "helloworld3.html" -> helloworld3()
            else -> println(title)
        }
    })
}

fun main(args: Array<String>) {
    println("Welcome to Kotlin for JavaScript!")
    boombayah()
}

Knockout.kt

package okoko
import kotlin.browser.document
import kotlin.browser.window
external val ko: dynamic = definedExternally

object vm {
    fun ViewModel(first:String, last:String): dynamic {
        val me = this.asDynamic()
        me.firstName = ko.observable(first)
        me.lastName = ko.observable(last)
        me.fullName = ko.pureComputed({ "${me.firstName()} ${me.lastName()}" })
        return me
    }
}

fun helloworld2() {
    ko.applyBindings(vm.ViewModel("Knockout", "Cool"))
}

fun helloworld3() {
    val vm3 = js("{}")
    vm3.ViewModel = { first:String, last:String  ->
        vm3.firstName = ko.observable(first)
        vm3.lastName = ko.observable(last)
        vm3.fullName = ko.pureComputed({ "${vm3.firstName()} ${vm3.lastName()}" })
    }
    vm3.ViewModel("Knockout", "Again")
    ko.applyBindings(vm3)
}

index.html

<!doctype html>
<html>
<head>
<title>index.html</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.4.2.js"></script>
<script src="../build/kotlin-js-min/main/koko.min.js"></script>
<style>
    p {
      font-size: 200%;
      background-color: aliceblue;
    }
    </style>
</head>
<body>

  <p>If you click on me, you will be blessed.</p>

</body>
</html>

helloworld.html

<!doctype html>
<html>
<head>
<title>helloworld.html</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.4.2.js"></script>
<script src="../build/kotlin-js-min/main/koko.min.js"></script>
<style>
    body {
      font-size: 200%;
      background-color: aliceblue;
    }
    </style>
</head>
<body>

<p>First name: <input data-bind="value: firstName" /></p>
<p>Last name: <input data-bind="value: lastName" /></p>
<h2>Hello, <span data-bind="text: fullName"> </span>!</h2>

</body>
</html>

helloworld2.html

<!doctype html>
<html>
<head>
<title>helloworld2.html</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.4.2.js"></script>
<script src="../build/kotlin-js-min/main/koko.min.js"></script>
<style>
    body {
      font-size: 200%;
      background-color: aliceblue;
    }
    </style>
</head>
<body>

<p>First name: <input data-bind="value: firstName" /></p>
<p>Last name: <input data-bind="value: lastName" /></p>
<h2>Hello, <span data-bind="text: fullName"> </span>!</h2>

</body>
</html>

helloworld3.html

<!doctype html>
<html>
<head>
<title>helloworld3.html</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.4.2.js"></script>
<script src="../build/kotlin-js-min/main/koko.min.js"></script>
<style>
    body {
      font-size: 200%;
      background-color: aliceblue;
    }
    </style>
</head>
<body>

<p>First name: <input data-bind="value: firstName" /></p>
<p>Last name: <input data-bind="value: lastName" /></p>
<h2>Hello, <span data-bind="text: fullName"> </span>!</h2>

</body>
</html>

Live Demos

https://cloud.ibinti.com/file/ko4js/index.html

https://cloud.ibinti.com/file/ko4js/helloworld.html

https://cloud.ibinti.com/file/ko4js/helloworld2.html

https://cloud.ibinti.com/file/ko4js/helloworld3.html

Leave a Reply

Your email address will not be published. Required fields are marked *