Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom methods of Web components

It is possible to define custom functions on custom elements?

Something like:

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

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

And calling the method on the element:

var istance = document.createElement('custom-el');
instance.customMethod();
like image 392
TheGr8_Nik Avatar asked Sep 11 '16 18:09

TheGr8_Nik


1 Answers

Yes, of course.

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

New answer for Custom Elements v1

class CE extends HTMLElement {
  customMethod() {
    console.log( 'customMethod called' )
  }
}

customElements.define( 'custom-el', CE )

var instance = document.createElement( 'custom-el' )
instance.customMethod()

Old answer for Custom Elements v0 (deprecated)

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();
like image 121
Supersharp Avatar answered Oct 17 '22 14:10

Supersharp