Reputation: 582
How can i send data from client to server using html5 webcomponent
setting up data from server to client, is very easy, works like a charm how ever cannot find solution to send data to server
Please assist, but Iam not going to use Lit or Polymer
#JavaScript
class SimpleComponent extends HtmlElement {
connectedCallback() {
this.innerHTML = '<input type="text" id="test"/>";
this._input = this.querySelector('#test');
this._input.onchange = function() {
***** i want to send the value to server ****
})
}
setInputValue(value) {
this._input.value = value;
}
}
customElements.define("simple-com",SimpleComponent);
Now Java at Server
@Tag("simple-com")
class SimpleComponent extends Component {
public SimpleComponent() {
}
public void setValue(String value) {
getElement().callJsFunction("setValue",value);
}
}
Upvotes: 1
Views: 371
Reputation: 8001
The main challenge compared to Polymer or LitElement is that an event handler defined using the pattern innerElement.onchange = function() {}
will not be run with this
referencing the custom element instance. This in turn means that trying to use this.$server
won't work because this
isn't pointing to the expected value even though $server
is indeed present in the place where it's supposed to be.
The easiest way of fixing this is to change the code to use an arrow function (() => {}
) instead of an explicit function
. This works because arrow functions inherit this
from the scope where the function is defined whereas explicit functions have this
defined in different ways depending on how it is run. Another approach would be to store a reference to this
in a separate variable (e.g. let root = this
) and then reference that variable instead of this
in the function (e.g root.$server.doSomething()
).
Putting everything together, this is what the code looks like with my modifications to make everything work.
class SimpleComponent extends HTMLElement {
connectedCallback() {
this.innerHTML = '<input type="text" id="test"/>';
this._input = this.querySelector('#test');
this._input.onchange = () => {
this.$server.handleChange(this._input.value);
};
}
setValue(value) {
this._input.value = value;
}
}
customElements.define("simple-com", SimpleComponent);
Upvotes: 2