Calling Instance Methods on JSObject #92746
Unanswered
SerratedSharp
asked this question in
Show and tell
Replies: 1 comment
-
I've setup a repo containing snippets/recipes covering this and other JS interop scenarios: It also briefly mentions the nuget package I published that demonstrates in greater detail some of these approaches that help eliminate the need for so much boilerplate JS/C# proxy/shim code. |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
To my knowledge to call an instance method on a JSObject instance requires scaffolding a static JS method and a static C# method to import that, to act as proxies for the instance methods, taking the JSObject to be called on as a parameter. Doing multiple instance methods this way requires alot of plumbing.
To ease the implementation I basically use a method that takes a JSObject instance, a function name, and any number of parameters. Using JS .apply I can pass any number of params to the instance method.
A helper method for leveraging the above. I actually have several layers of these, some using [CallerMemberName] to get me the point where I can just have methods on my C# instance wrappers named to match the JS instance
Usage:
This is pretty loosely typed, but there's already a level of trust that the type bindings declared in JSImport is consistent with what is assumed/expected from the underlying JS method. So all we're doing is moving the declaration of specific types up a couple levels to save us from have a huge multitude of static proxy methods.
It also allows me to write wrappers for JS instances exposed by libraries without writing any javascript beyond the one FuncByNameToObject, at least for all of its instance methods.
This is a simplified example. In practice I use several layers of methods with things like [CallerMemberName] to make it where the call to the underlying type is inferred from the C# caller's name, which makes it really easy to create a proxy for a JS type with a large surface area without alot of plumbing. I'm cleaning up the approach and am thinking it might make a nice little library on its own.
Beta Was this translation helpful? Give feedback.
All reactions