I am converting a website from Angular to Web components/polymer. What I need is to call a function called lookupUser()
when a form is submitted. However I'm not sure how to define the function properly.
(just the relevant) HTML
<form name="userLookupForm" class="search" onsubmit="lookupUser();">
Javascript
(function(customElements) {
class DashboardSearch extends PolymerMixins.LightDomMixin(Polymer.Element) {
static get is() {
return 'dashboard-search';
}
static get config() {
return {
properties: {
user: {
type: Object
},
},
};
}
lookupUser() {
if (scope.userlookup) {
$state.go('users', {
query: scope.userlookup
});
}
};
}
customElements.define(DashboardSearch.is, DashboardSearch);
})(window.customElements);
Ignoring the angular I have yet to remove from the function, how would I properly define this function so it can be called from onsubmit
?
In Polymer templates, event listeners can be added declaratively using the on-*
annotation syntax. Instead of onsubmit="lookupUser();"
you need to use on-submit="lookupUser"
. Note that the value is just the name of the method; no parentheses or data-binding brackets (on-submit="[[lookupUser]]"
is a very common mistake).
<form name="userLookupForm" class="search" on-submit="lookupUser">
Then, in your class, you want to define a lookupUser
method. Just like event listeners added with addEventListener
, it will receive a single argument, the Event object.
class DashboardSearch extends PolymerMixins.LightDomMixin(Polymer.Element) {
static get is() {
return 'dashboard-search';
}
static get config() {
// ...
}
lookupUser(event) {
console.log(event.target); // => logs <form> element
}
}
This is covered in the Handle and fire events section of the official docs.