Donald White
Donald White

Reputation: 81

ES6 Unable to use native setters when extending HTMLButtonElement

I'm trying to figure out how to use the native setters and getters for an extended HTMLButtonElement. Specifically the 'disabled' property.

The property is listed here: https://developer.mozilla.org/en-US/docs/Web/API/HTMLButtonElement

The example code is here: http://codepen.io/anon/pen/RWmKaw?editors=001

Pasted Code block from the link above:

'use strict';

class TestButton extends HTMLButtonElement {
  attachedCallback() {
    this.appendChild(document.createTextNode('test'));
    this.addEventListener('click', (event) => {
      this.customFun();
    });
  }

  customFun() {
    alert('setting myself as disabled.');
    this.disabled = true;
  }
}
document.registerElement('test-button', TestButton);

document.body.appendChild(document.createElement('test-button'));

When I access the disabled property when setting or getting I receive the following error:

Uncaught TypeError: Illegal invocation(anonymous function) @ pen.js:33

I am able to override the setter and getter for the TestButton, but that's not solving the problem, simply addressing the symptom.

I've also tried using the following syntax: codepen: http://codepen.io/anon/pen/NGVddj?editors=001

'use strict';

class TestButton {
  attachedCallback() {
    this.appendChild(document.createTextNode('test'));
    this.addEventListener('click', (event) => {
      this.customFun();
    });
  }

  customFun() {
    alert('setting myself as disabled.');
    this.disabled = true;
  }
}
document.registerElement('test-button', {prototype:TestButton, extends:'button'});

let myButton = document.createElement('button', 'test-button');
myButton.setAttribute('is', 'test-button');
myButton.customFun();
document.body.appendChild(myButton);

This just results in the stripping of my custom elements functions, and I receive an error:

Uncaught TypeError: myButton.customFun is not a function

Upvotes: 1

Views: 1587

Answers (1)

Donald White
Donald White

Reputation: 81

Ok I solved it:

'use strict';

class TestButton extends HTMLButtonElement {
  attachedCallback() {
    this.addEventListener('click', (event) => {
      this.customFun();
    });
  }

  customFun() {
    alert('setting myself as disabled.');
    this.disabled = true;
  }
}
document.registerElement('test-button', {
  prototype: TestButton.prototype,
  extends: 'button'
});

let myButton = document.createElement('button', 'test-button');

document.body.appendChild(myButton);

The trick is still extending HTMLButtonElement to gain the ability to inherit the parents' properties, but then within the register, using the TestButton.prototype, and extends syntax fixes it in combination with the create element syntax.

Also the removal of the 'is' solved it.

Upvotes: 3

Related Questions