Introduction

Installation

Frequently asked questions

Syntax, keywords and built-in functions

Standard distribution

import implementation

Brython packages

Browser interface

Brython-specific built-in modules

Working with Brython

Cookbook

 

The module browser.webcomponent is used to create custom HTML tags, using the standard DOM WebComponent technology.

A custom element can be used in the HTML page as

<popup-window>Hello !</popup-window>

The module exposes the following functions

define(tag_name, component_class)

tag_name is the name of the custom tag name. The Web Component specification mandates that the tag name includes a dash (the "-" character).

component_class is the class that defines the component behaviour. Its __init__ method is called to create the component; the parameter self references the DOM element for the custom component.

get(tag_name)

returns the class associated to tag_name, or None.

Example

Suppose we want to define a custom tag <bold-italic> with an attribute "data-val":

<bold-italic data-val="hello"></bold_italic>

What happens when the tag is found in the HTML document is defined by the method __init__ of the Web Component class BoldItalic.

from browser import webcomponent

class BoldItalic:

    def __init__(self):
        # Create a shadow root
        shadow = self.attachShadow({'mode': 'open'})

        # Insert the value of attribute "data-val" in bold italic
        # in the shadow root
        shadow <= html.B(html.I(self.attrs['data-val']))

# Tell the browser to manage <bold-italic> tags with the class BoldItalic
webcomponent.define("bold-italic", BoldItalic)

Note the use of another DOM technology, ShadowRoot, to define a DOM subtree, different from the main DOM tree.

Life cycle management

The Web Component defines a set of callback functions that manage the life cycle of a custom component.

To implement them in Brython, just add the functions in the class definition:

import browser.webcomponent

class BoldItalic:

    def __init__(self):
        # Create a shadow root
        shadow = self.attachShadow({'mode': 'open'})

        # Insert the value of attribute "data-val" in bold italic
        # in the shadow root
        shadow <= html.B(html.I(self.attrs['data-val']))

    def connectedCallback(self):
        print("connected callback", self)

webcomponent.define("bold-italic", BoldItalic)