Пользовательские методы веб-компонентов

Можно ли определить пользовательские функции для пользовательских элементов?

Что-то типа:

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

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

И вызов метода для элемента:

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

person TheGr8_Nik    schedule 11.09.2016    source источник


Ответы (1)


Да, конечно.

Ваш пример работает, как вы можете видеть в фрагменте кода ниже:

Новый ответ для пользовательских элементов v1

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

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

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

Старый ответ для Custom Elements v0 (устаревший)

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();

person Supersharp    schedule 11.09.2016
comment
@Mariusz да, это работало для пользовательских элементов v0, но теперь они устарели ... Я обновил код. - person Supersharp; 19.06.2020