Click here to Skip to main content
12,359,102 members (33,725 online)
Click here to Skip to main content

Stats

158.1K views
5.3K downloads
111 bookmarked
Posted

JavaScriptBuilder: JavaScript Handler Class for Custom Controls

, 2 Sep 2003
The conflict between maintenance and efficiency examined and resolved.
using System;
using System.Text;

namespace CP.WebControls
{
	/// <summary>
	/// Create well formatted or completely unformatted javascript
	/// code with minimal effort.
	/// </summary>
	public class JavaScriptBuilder
	{
		private StringBuilder sb = new StringBuilder();
		private int currIndent = 0;
		private int openBlocks = 0;
		private bool format = false;

		/// <summary>
		/// Instantiate a JavaScriptWriter for unformatted code
		/// </summary>
		public JavaScriptBuilder()
		{
		}

		/// <summary>
		/// Instantiate a JavaScriptWriter with Formatted switch
		/// </summary>
		/// <param name="Formatted">Format Code?</param>
		public JavaScriptBuilder(bool Formatted)
		{
			format = Formatted;
		}

		/// <summary>
		/// Current level of indent
		/// </summary>
		public int Indent
		{
			get { return currIndent; }
			set { currIndent = value; }
		}

		/// <summary>
		/// Add a line of code
		/// </summary>
		/// <param name="parts">Parts of the line as array of strings</param>
		public void AddLine(params string[] parts)
		{
			// Open line with tabs, where formatting is set
			if (format)
				for (int i=0; i < currIndent; i++)
					sb.Append("\t");

			// Append parts of the line to StringBuilder individually
			// - much more efficient than sb.AppendFormat
			foreach (string part in parts)
				sb.Append(part);

			// Append a new line where formatting is set or a space
			// where it isn't
			if (format)
				sb.Append(Environment.NewLine);
			else
				if (parts.Length > 0)
					sb.Append(" ");
		}

		/// <summary>
		/// Open a code block and increase indent level
		/// </summary>
		public void OpenBlock()
		{
			AddLine("{");
			currIndent++;
			openBlocks++;
		}

		/// <summary>
		/// Close code block and decrease indent level
		/// </summary>
		public void CloseBlock()
		{
			// Check that there is at least one block open
			if (openBlocks < 1)
				throw new InvalidOperationException("JavaScriptBuilder.CloseBlock() called when no blocks open");

			currIndent--;
			openBlocks--;
			AddLine("}");
		}

		/// <summary>
		/// Add a comment line to the code, where formatting is set
		/// </summary>
		/// <param name="CommentText">Parts of the comment as an array of strings</param>
		public void AddCommentLine(params string[] CommentText)
		{
			if (format)
			{
				// Open the line with tab indent
				for (int i=0; i < currIndent; i++)
					sb.Append("\t");

				// ... and a comment marker
				sb.Append ("// ");

				// Append all the parts of the line
				foreach (string part in CommentText)
					sb.Append(part);

				// Throw in a new line
				sb.Append(Environment.NewLine);
			}
		}

		/// <summary>
		/// Convert to string (adding script start and end tags)
		/// </summary>
		/// <returns>Inner script text</returns>
		public override string ToString()
		{
			// Check that each indent has a matching outdent
			// - if not then there's almost certainly a problem in the javascript
			if (openBlocks > 0)
				throw new InvalidOperationException("JavaScriptBuilder: code blocks are still open");

			// Add the <script> tags and some comment blocks, so that
			// browsers that don't support scripts will not crash horribly
			return String.Format(
				"<script language=\"javascript\">{0}<!--{0}{1}// -->{0}</script>", 
				Environment.NewLine, 
				sb
			);
		}
	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

Paul Riley
Web Developer
United Kingdom United Kingdom
Paul lives in the heart of En a backwater village in the middle of England. Since writing his first Hello World on an Oric 1 in 1980, Paul has become a programming addict, got married and lost most of his hair (these events may or may not be related in any number of ways).

Since writing the above, Paul got divorced and moved to London. His hair never grew back.

Paul's ambition in life is to be the scary old guy whose house kids dare not approach except at halloween.

You may also be interested in...

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.160621.1 | Last Updated 3 Sep 2003
Article Copyright 2003 by Paul Riley
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid