Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Need a JSObject property to be bound to jsexported methods #206

Open
sammy44nts opened this issue Mar 23, 2021 · 1 comment
Open

Need a JSObject property to be bound to jsexported methods #206

sammy44nts opened this issue Mar 23, 2021 · 1 comment

Comments

@sammy44nts
Copy link

Hello!

Using Kotlin, I'm having trouble with the 'proper' way to define the JSObject property because Property constructor is private so I can't declare them that way.

I used

        JSObjectPropertiesMap(instance, Any::class.java).apply {
            put("id", instance.getId())
        }

to define a property in the JSObject.

I need the property to use getId() as getter and setId(value) as setter. Do you see a way to redefine JS object property id to bind it to the jsexported getter & setter at the instance creation time in the constructor?

@sammy44nts
Copy link
Author

sammy44nts commented Mar 26, 2021

Found a solution for two way communication:

  • getId() & setId(value) are not exported using jsexport anymore;
  • At instance creation time, I retrieve the Kotlin member id:
    var id: String
        get() = getId()
        set(value) = setId(value)
  • Set the constructor's properties:
    this::class.memberProperties.forEach {
      if (it.name == "id") {
        `this`.property(
          "\$\$_getid",
          object : JSFunction(context, "__NativeGetter__") {
            fun __NativeGetter__() = it.getter.call(this)
          })
        `this`.property(
          "\$\$_setid",
          object : JSFunction(context, "__NativeSetter__") {
            fun __NativeSetter__(v: JSValue) {
              if (it is KMutableProperty<*>) it.setter.call(this, "$v")
            }
          })
      }
    }
  • Use of the following to redefine JSObject prototype:
    context.evaluateScript(
      "function InitClass(Class, props) {\n" +
      "    props.forEach(prop => {\n" +
      "        Object.defineProperty(Class.prototype, prop, {\n" +
      "                    get: function () {return this[\"\$\$_get\"+prop]()},\n" +
      "                    set: function (v) {this[\"\$\$_set\"+prop](v)}\n" +
      "                });\n" +
      "    });\n" +
      "}"
    )
  • Call of context.evaluateScript("InitClass($className, ['id'])")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant