1

I am building a desktop app using node+electron. I needed a way to containerize my UI elements in the DOM.

I came up with this solution that can be extended by other Typescript DOM elements.

My code runs effectively. Is this an appropriate use of Typescript?

Am I rewriting a library that someone else has already written? I didn't use React because it doesn't allow object scoped global variables.

Is it bad form to parse HTML on the front end?

class Glyph {
//field
uuid:string;

//constructor
constructor(parent:string, html:string) {
    this.uuid = this.guid();

    var regex = /(<([^>]+>))/ig
    var tags = html.match(regex);

    var position = tags[0].search(/>/ig);
    tags[0] = [tags[0].slice(0, position), ' id="'+ this.uuid +'"', tags[0].slice(position)].join('');
    html = tags.join('');

    //appends child to the provided parent id
    document.getElementById(parent).innerHTML += html;
}

guid():string {
    return this.s4() + this.s4() + '-' + this.s4() + '-' + this.s4() + '-' +
        this.s4() + '-' + this.s4() + this.s4() + this.s4();
}

s4():string {
return Math.floor((1 + Math.random()) * 0x10000)
    .toString(16)
    .substring(1);
}

replaceElement(html):void {
    var currentElement = document.getElementById(this.uuid);
    currentElement.outerHTML = html;
}

deleteElement():void {
    var child = document.getElementById(this.uuid);
    var parent = document.getElementById(this.uuid).parentElement;
    parent.removeChild(child);
}

}

1 Answers1

1

The blasphemy of parsing HTML with Regex aside, this is a strange pattern. Adding and removing elements like this will become expensive as your application grows in size. React does a similar thing in concept, but in practice their virtual DOM let's them modify the actual DOM more cheaply by making changes in bulk. Why not use React? It already does what you're trying to accomplish here and more. What do you mean by object scoped global variable?

Michael Wu
  • 1,177
  • 1
  • 13
  • 34
  • I think you're right about the performance hit. By 'object scoped global variable' I mean variables that are available inside the object instance and are scoped to the instance. AFAIK that isn't available in React. – dangerousfood Aug 08 '17 at 18:30
  • Both instance (scoped to instance of a class) and static (scoped to class) variables are available to _TypeScript_. React doesn't come into play here. – Michael Wu Aug 08 '17 at 18:34