Web Component Custom Methods

Can I define custom functions on custom elements?

Sort of:

var proto = Object.create(HTMLElement.prototype);
proto.customMethod = function () { ... };

document.registerElement('custom-el', {
  prototype: proto
});

And the method call for the element:

var istance = document.createElement('custom-el');
instance.customMethod();
+4
source share
1 answer

Yes of course.

Your example works as you can see in the code snippet below:

var proto = Object.create(HTMLElement.prototype);
proto.customMethod = function() {
  console.log('customMethod called')
};

document.registerElement('custom-el', {
  prototype: proto
});
var instance = document.createElement('custom-el');
instance.customMethod();
Run codeHide result
+3
source

Source: https://habr.com/ru/post/1654283/


All Articles