LinusU / swift-napi-bindings

MIT License
29 stars 0 forks source link

More examples/documentation request #2

Open paulbatessonos opened 4 years ago

paulbatessonos commented 4 years ago

Hey @LinusU! This package looks awesome, but beyond the simple examples it gets to be quite the exercise of seeing how you structured things. I'd love to use this package more but more advanced cases have me lost at present.

I've got a Swift class I'm defining that needs to event back to JS, through a EventEmitter.emit(...). EventEmitter's prototype is added to the NAPI class through utils.inherit(...) on the JS side before instantiation. I'm having a hard time seeing how this is possible without the object's receiver one would use with napi_call_function?

Here's the TypeScript...


import * as utils from 'utils'
import { BindingClass } from ('.build/release/binding')

util.inherits(BindingClass, events.EventEmitter)

export { BindingClass }

You see, I need to access the emit function added to the BindingClass prototype.

class BindingClass: NSObject {
    init(_ env: OpaquePointer) { ... }

    func fireEvent(name: String) {
        let emit = /* ... get JS emit function from self */

        // Emit event
        emit.call(env, name)
    }
}

Any chance of more docs or examples with classes?

camhart commented 4 years ago

I second this!

LinusU commented 4 years ago

Sorry for not getting back to you earlier 🙈

I would love to publish some more examples & proper documentation, but at the moment I'm swamped with other things though.

In the specific case you mentioned, I think that you need to pass in a handle to the function. I would expose a function called something like registerEmitFunction which you can call from the JS part. Then you can save that handle and call it later, passing the proper object for this:

import * as utils from 'utils'
import { registerEmitFunction, BindingClass } from ('.build/release/binding')

registerEmitFunction(events.EventEmitter.prototype.emit)
util.inherits(BindingClass, events.EventEmitter)

export { BindingClass }