2017-08-08 51 views
1

我正在使用node + electron構建桌面應用程序。我需要一種方法來容納我在DOM中的UI元素。在前端解析HTML是不是很糟糕的形式?

我想出了可以被其他Typescript DOM元素擴展的解決方案。

我的代碼有效運行。這是否合適使用Typescript?

我在改寫其他人已經寫過的圖書館嗎? 我沒有使用React,因爲它不允許對象範圍的全局變量。

在前端解析HTML是不是很糟糕的形式?

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

https://stackoverflow.com/a/1732454/1687909 – Mogzol

+6

瀏覽器實際上是一個HTML解析器 –

+0

React不允許對象範圍的全局變量?你是什​​麼意思? – azium

回答

1

一邊用正則表達式解析HTML的褻瀆,這是一個奇怪的圖案。隨着應用程序規模的增大,添加和刪除這樣的元素將變得非常昂貴。 React在概念上做了類似的事情,但實際上他們的虛擬DOM讓他們通過批量修改更便宜地修改實際的DOM。爲什麼不使用React?它已經完成了你在這裏嘗試完成的任務。你是什​​麼意思object scoped global variable

+0

我認爲你的表現是正確的。 '對象作用域全局變量'是指對象實例內可用的變量,它們的作用域是實例。 AFAIK在React中不可用。 – dangerousfood

+0

_TypeScript_可以使用實例(範圍爲類的實例)和靜態(範圍爲類)變量。 React在這裏不起作用。 –

相關問題