alesgenova / post-me

📩 Use web Workers and other Windows through a simple Promise API

Home Page:https://www.npmjs.com/package/post-me

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Allow using classes to implement local methods

birtles opened this issue · comments

Is your feature request related to a problem? Please describe.
I would like to provide a class instance to implement local methods, e.g.

class MyThing {
  private localState = 'abc';

  doStuff() {
    return this.localState;
  }
}

const thing = new MyThing();
ClientHandshake(messenger, thing);

However, due to the way local methods are invoked, attempting to do the above will fail when invoking doStuff from the other end because this.localState will be undefined.

Describe the solution you'd like
If we could make the following line from handles.ts:

const method = this._methods[methodName];

do something like:

const method = this._methods[methodName].bind(this._methods);
// (Presumably this would need to go after the part where we check if
// `method` is a function or not)

then I think this would allow using class instances.

Describe alternatives you've considered
The alternative is the client has to wrap their class instance in such a way that all methods get bound to the class instance. post-me could provide such a utility, I suppose.

I'm happy to work on a PR for this if you agree with the problem and proposed solution.

I didn't even considered that a class instance could be passed as the methods parameter, but I can see how it is a totally legit use case to have shared state across methods. Thank you for spotting the issue!

I would be against manually binding this from within post-me, because the user might have already bound it to something else.

However, I did a quick test, and found a possible solution that should keep every use case working:

Current behavior:

const method = this._methods[methodName];
method(); // method is not bound to the instance

Proposed behavior:

this._methods[methodName]() // the method is still bound to the instance

Do you see any problem with this approach?

I will more than welcome a PR if you want to take this on!

I would be against manually binding this from within post-me, because the user might have already bound it to something else.

Oh, very good point!

Proposed behavior:

this._methods[methodName]() // the method is still bound to the instance

Yes, that sounds good. I will make up a PR for this.