preact-custom-element icon indicating copy to clipboard operation
preact-custom-element copied to clipboard

Exposing public properties?

Open bestguy opened this issue 9 years ago • 7 comments

Hi, great library. I have a question on how to expose properties of a component to the DOM. It looks like you are iterating through the attributes to expose as the CustomElement prototype:

https://github.com/bspaulding/preact-custom-element/blob/master/src/index.js#L6

but am a little confused on what these would actually be. I mistakenly assumed I'd be able to define properties on the Preact component and automatically export them:

class Example extends Component {
  report() {
    console.log('SOUND OFF!')
  }
  render() {
    ...
}

However this does not work:

var example = $('x-example')[0];
example.report();

What would be the best way to do this?

bestguy avatar Sep 04 '16 22:09 bestguy

Hi @bestguy - I believe you might be able to do that using the ._component property:

var example = $('x-example')[0]._component;
example.report();

developit avatar Oct 09 '16 22:10 developit

Thanks @developit - I'm a little weak on web components, but was looking at Polymer docs (https://www.polymer-project.org/1.0/docs/devguide/instance-methods) and it allows this syntax:

Polymer({
    ...
    speak: function() {
      console.log(this._says);
    }
});

And call like so:

var cat1 = document.querySelector('cat-element');
cat1.speak();

without the ._component

Any tips on how I might modify this to support?

bestguy avatar Oct 10 '16 03:10 bestguy

I think we'd just iterate over the methods on the component's prototype and hoist them (skipping the builtins like render() and constructor(). Actually shouldn't be too hard at all.

developit avatar Oct 23 '16 17:10 developit

I've opened a PR to possibly address this. Initially I was using Object.getOwnPropertyNames to introspect as @developit mentioned, but I backed that out to an explicit list the user would pass in.

Just trying to allow the user retain some control over privacy, even though this is JS. :)

Thoughts / comments welcome there, I could go either way. Would be easy enough to introspect on your own and pass that into the explicit api, so I'm leaning that way. /shrug

bspaulding avatar Mar 19 '18 18:03 bspaulding

I have created a sample repo with react hooks where accessing the exposed methods does not work unfortunately. I would love to get a proposal on how to fix this.

https://github.com/rburgst/preact-web-component-method

rburgst avatar Aug 03 '21 06:08 rburgst

@developit could you share some insight here?

rburgst avatar Jan 25 '22 08:01 rburgst

I came across a similar problem as @rburgst. The preact-custom-element documentation refers to its register function but there is still no way to call a method on the web component from outside. Has there ever been a solution to this?

floriankuc avatar Jun 05 '22 21:06 floriankuc