Skip to content

Callable later pattern

Thomas Di Grégorio edited this page Sep 22, 2016 · 2 revisions

Classes inherited from natives classes can't use the super() keyword as the parent class is non intanciatable. Also class created with es6 class keyword can't be fake instanciated with Class.apply( another ) it MUST be instanciated with new keyword. So to go around this, as Jilex needs to extend Nodes that are already created (by the main DOMParser on load) it will call the Class method. Class method is a normal method that have the same name (case-sensitive) as the class. The Class method

my.Element = class MyOwnElement extends html.Element {
    constructor()
    {
        // must not call super() !!
        // instead act like a factory and return a new Node or Element
        return new Node('my:Element').extends( MyOwnElement ).MyOwnElement()
    }
    MyOwnElement()
    {
        this; // is the node created or extented
        super.Element() // call the Class method from the super
        // initialize like you'd did in the constructor
    }
}
...
<html ... xmlns:my="my.*">
    ...
    <my:Element id="owned"/>
    ...
</html>

You can later test

owned instanceof my.Element                          // true
owned instanceof Node                                // true
owned.Class === my.Element                           // true
owned.constructor.name === "MyOwnElement"            // true
typeof owned[owned.constructor.name] === "function"  // true

On DOMContentLoaded, Jilex will try to call the Class method:

node.Class && node.extends();
node[node.constructor.name] && node[node.constructor.name]();