quickjs-kt icon indicating copy to clipboard operation
quickjs-kt copied to clipboard

Sample for invoking js function in kotlin with params

Open yushaye opened this issue 1 year ago • 6 comments

This project is very helpful, but I have no idea about invoking js function in kotlin with params, can you add a sample for that.

yushaye avatar Aug 07 '24 10:08 yushaye

I need that too, @dokar3, Could you help us.

Greatwallcorner avatar Sep 03 '24 14:09 Greatwallcorner

@yushaye @Greatwallcorner Does this part help you?

stephanepechard avatar Sep 12 '24 14:09 stephanepechard

@yushaye @Greatwallcorner Does this part help you?

this example is define function in kotlin and invoke it in evaluate function, it couldn't provide some params , unless do some conversions youself(like kotlin array to json str?). the lib can't invoke a js function from kotlin with params

Greatwallcorner avatar Sep 13 '24 02:09 Greatwallcorner

@Greatwallcorner With the function method, you can have params in JS that you retrieve in Kotlin callback. What API would you like it to be?

stephanepechard avatar Sep 13 '24 10:09 stephanepechard

@Greatwallcorner With the function method, you can have params in JS that you retrieve in Kotlin callback. What API would you like it to be?

i didn't understand actually, could you give a example? This is my scene, first load js file via evaluate function, then i should able to invoke the function defined in that js file loaded before, and then i want to pass params from kotlin(these params may be param of kotlin function) to invoke js function. thanks for you reply.

Greatwallcorner avatar Sep 13 '24 12:09 Greatwallcorner

@Greatwallcorner If you put a function in the JS context through evaluate, you then have to use it again with the same context to get the result. But I do it simply on with only one evaluate call, like:

function evaluate(params) {
    // do something with params
}
evaluate(myParamsObject);

Then in Kotlin, I do:

val result = quickJs {
    define("myParamsObject") {
        property("param1") {
            getter {
                "This is my first param."
            }
        }
        property("param2") {
            getter {
                123
            }
        }
    }
    evaluate<OutputType>(script)
}

and if you need dynamic data in getters, you can use an callback to fetch them back in Kotlin.

stephanepechard avatar Sep 19 '24 16:09 stephanepechard