When developing webcontrol in Asp.net, the render method is used to present the control. In JavaScript, the concatenation of Some HTML code is usually handled by adding strings. This has the following drawbacks:
1. Poor readability, error-prone, and hard to detect after an error.
2. When Javascript is minimized, long strings cannot be minimized.
So in the project, I implemented the exhausting render method to process HTML code splicing.
StringBuilder = function () {var self = this,strs = [];self.append = function (str) {strs.push(str);};self.toString = function () {return strs.join("");};self.dispose = function () {strs = null;};},TextElement = function (text) {this.text = text;this.render = function () {return this.text;};},HtmlElement = function (tagName, innerText, attributes) {var self = this,halfTags = { br: true, img: true, hr: true, input: true };self.tagName = tagName || "div";self.attributes = attributes || {};self.innerText = innerText || "";self.children = [];if ($.isPlainObject(innerText)) {self.innerText = "";self.attributes = innerText;}self._isShortTag = false;if (halfTags[self.tagName] === true) {self._isShortTag = true;}self.render = function () {var sb = new StringBuilder(),html = "";sb.append(self._renderBeginTag(self.tagName, self.attributes));if (self.innerText !== "") {sb.append(self.innerText);}if (self.children.length > 0) {$.each(self.children, function (index, ele) {sb.append(ele.render());});}sb.append(self._renderEndTag(self.tagName));html = sb.toString();sb.dispose();return html;};self.add = function (ele) {this.children.push(ele);};self._renderBeginTag = function (tagName, attributes) {var sb = new StringBuilder(),strRet = "";sb.append("<");sb.append(tagName);$.each(attributes, function (key, value) {sb.append(" ");sb.append(key);sb.append("=");sb.append("\"");sb.append(value.toString());sb.append("\"");});if (this._isShortTag) {sb.append(" ");} else {sb.append(">");}strRet = sb.toString();sb.dispose();return strRet;};self._renderEndTag = function (tagName) {var sb = new StringBuilder(),strRet = "";if (this._isShortTag) {sb.append("/>");} else {sb.append("</");sb.append(tagName);sb.append(">");}strRet = sb.toString();sb.dispose();return strRet;};};
At the top, a stringbuilder class is implemented in JavaScript. Process String concatenation. The following method is used to call the class htmlelement.
var div = new HtmlElement("div", {class:"divcss"});var innertextbox = new HtmlElement("input", {type:"text"});div.add(innertextbox);var str = div.render();
The result of STR is:
<div class="divcss"><input type="text" /></div>
You can encapsulate textbox and some common HTML elements into methods to improve code reusability, reduce code size, and facilitate maintenance.