Use A Builder With JavaScript In WebParts

It is pretty easy to use JavaScript in your WebParts, and people that know me, know I frickin despise JavaScript. I really, really do. I know sometimes I have to use it, but I would prefer if it didn’t exist, even though I might start warming up to our old friend as Orcas since it is supposed to have better debugging and intellisense support (finally). Outside of my personal disdain for it, sometimes I have to use JavaScript (thanks to Trenton Kuzman who wrote my last script for my last WebPart at CENTAF:-) ), and I usually build it out by using an ArrayList object and passing it into a builder method so that I hydrate the builder object in my primary WebPart class file (which traditionally for this layer of abstraction would be kept in a custom WebPart base class that instead inherits from the WebPart base class, assimilated into your WebPart class file subsequently).

So basically, I want to be able to do this in an arbitrary WebPart class file:

[csharp]

private void BuildExampleJavaScript (TextWriter oWriter)
{
oWriter.Write(“Do Something“, ID);

// This is my function below, now I want to add some statements
JavaScriptBuilder l_oBuilder = new JavaScriptBuilder();
l_oBuilder.AddStatement(“function buenz_ExampleFunction(id){“);
l_oBuilder.AddStatement(“try{‘arbitrary Statements}”);
oWriter.Write(l_oBuilder.ScriptString);
}

[/csharp]

It is cleaner to me. So I use this class file:

[csharp]

using System;
using System.Collections;
using System.Text;

namespace buenz.Examples
{
public class JavaScriptBuilder : IJavaScriptBuilder
{
private readonly ArrayList m_oStatements = new ArrayList();

public void AddStatement(string line)
{
m_oStatements.Add(line);
}

public string ScriptString
{
get
{
StringBuilder l_oBuilder = new StringBuilder(100);
l_oBuilder.Append(““);
return l_oBuilder.ToString();
}
}
}
}

[/csharp]

and then this interface (to adhere to Design by Contract programming principles):

[csharp]

namespace buenz.Example
{
public interface IJavaScriptBuilder
{
string ScriptString { get; }

void AddStatement(string strLine);
}
}

[/csharp]

which let’s me do what I want to accomplish. It looks cleaner and provides finer seperation IMHO.

Share