preact-custom-element
preact-custom-element copied to clipboard
Exposing public properties?
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?
Hi @bestguy - I believe you might be able to do that using the ._component property:
var example = $('x-example')[0]._component;
example.report();
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?
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.
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
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
@developit could you share some insight here?
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?