Embind makes it extremely easy to create interface bindings that allow Javascript code to interact with native code. However, usage of the generated API is often stylistically inclined more toward C++ than Javascript. With a couple of small touches, we can create interfaces with a more Javascript-flavoured API, that feel right at home alongside other Javascript libraries.
Assume that we have a class that supports using the observer pattern for notifying other objects of changes to its state:
We can allow the use of Javascript functions as observers, by creating a simple adapter class:
Assuming that we expose the following interface bindings:
We can then add function callbacks like so:
Key-value structures for configuration
Many Javascript libraries involve a single setup step that accepts a large number of configuration options, passed as a single object containing key-value mappings. This is quite straightforward to implement with Embind.
Assume we want to support the following usage from Javascript:
We can support this usage with Embind by performing a little type jugging:
Any values that are missing, or of the wrong type, will simply be ignored. Combined with the code from above to facilitate the use of Javascript function callbacks, this allows our native library wrapper interface to support a stylistic usage similar to any other Javascript library.