Nada
Nada

Reputation: 21

Custom methods and properties of html5 custom elements

My question is about the proper way of adding my own logic to custom elements.

I know how to create custom element, define a class extending HTMLElement, define callbacks like connectedCallback. It works.

The question is: how am I supposed to create my own methods and properties to support my custom logic? As I understand, defining them directly in my custom element class might cause conflict with current (or future) HTMLelement properties and methods.

Upvotes: 2

Views: 1097

Answers (2)

Intervalia
Intervalia

Reputation: 10945

1: Avoid any well known properties or functions unless you want to override them. If you are overriding them and you still want the old code to function make sure to call super in your functions, getters and setters.

2: Don't worry about future changes until they happen. Honestly there are not many changes to HTMLElement that will happen in each version of the language upgrade. Personally I just don't worry about it. I define whatever properties and functions I want. I often don't even worry about the existing functions.

For example I will use get title() and set title() and I won't bother calling super. Yes, I know I am breaking the existing model, but it doesn't matter for the component I did that to.

Please don't use the underscore '_' for public function names since the tradition is that those are supposed to be private functions and properties and should never be called by someone using the element.

Just write what you need to write. If someone using my component ever needed the original title functionality to work then I would fix it, but that will probably never be the case.

Upvotes: 4

Supersharp
Supersharp

Reputation: 31171

You can define them directly in the custom element class.

If you don't want them to cause confict with future properties and method, you can add a prefix like : underscore "_", "my".

class MyCustomElement extends HTMLElement {
    constructor() {
        super()
        _init()
    }
    _init() {
        this.attachShadow( {mode: 'open' } )
    }
}

You could also create your own classes according to an design model. For example, if you use the MVC design pattern, you can create the class View, Model, Controller...

Upvotes: 1

Related Questions