electron icon indicating copy to clipboard operation
electron copied to clipboard

Remove all listeners for a plugin

Open hampoelz opened this issue 2 years ago • 7 comments

Match removeAllListeners() function with Capacitor API to remove all listeners of a plugin.

Refs #137

hampoelz avatar Apr 21 '22 13:04 hampoelz

Is there any documentation on how to use events on a Capacitor Electron plugin? I'm still having issues understanding how to use/implement this, and can't find any implementation examples.

matallui avatar May 11 '22 15:05 matallui

@matallui You can find a small example in the createplugin-documentation: https://github.com/capacitor-community/electron/blob/main/docs-site/docs/creatingplugins.md

hampoelz avatar May 11 '22 15:05 hampoelz

@hampoelz thanks! I have something similar but it's not working. I'm just confused what to put in each file of the plugin codebase.

src/definitions.ts:

export interface SomePlugin {
    echo(s: string): Promise<string>;
}

electron/src/index.ts

export class Some extends EventEmitter implements SomePlugin {
    echo(s: string): Promise<string> {
        return Promise.resolve(s);
    }
}

It sounds like the above example would let you do something like this, from the client code:

import { Some } from 'some-plugin';

const hello = await Some.echo('hello');

const id = Some.addListener('some-event', () => console.log('fired'));
Some.removeListener(id);

But the last two lines won't work because those methods are not implemented on the plugin.

I also don't understand what this means from the example:

CapacitorCustomPlatform.plugins.MyPlugin.addListener('my-event', console.log);

Where do I access CapacitorCustomPlatform from?

Any help is much appreciated!

matallui avatar May 11 '22 16:05 matallui

@matallui your code looks good to me.

If you're using Capacitor with the bundled Capacitor-Core you can access your plugin with Capacitor.Plugins.yourPlugin or on Electron with CapacitorCustomPlatform.plugins.yourPlugin. (Capacitor and CapacitorCustomPlatform are globally scoped)

(I'm using const myPlugin = Capacitor.Plugins.myPlugin || CapacitorCustomPlatform.plugins.myPlugin; to access my plugin cross-platform)

hampoelz avatar May 11 '22 19:05 hampoelz

@hampoelz thanks! I actually got it working by simply type casting the plugin to any:

import { Some } from 'some-plugin';

let listener: any;

listener = (Some as any).addListener('some-event', console.log).then(res => (listener = res));

// some code

if (listener) {
  if (listener.remove) {
    // iOS & Android
    listener.remove();
  } else {
    // electron case
    (Some as any).removeListener(listener);
  }
}

This is what is working for me right now.

I guess those methods are added at runtime, so Typescript was not letting me access methods that were not defined by the plugin. At least that's my take on this.

matallui avatar May 11 '22 20:05 matallui