Sys.StringBuilder.appendFormat(mask, args[])
I'm speaking this week at TechEd New Zealand, and TechEd Australia.
As part of my talk, I show how Microsoft AJAX offers object oriented LIKE behavior. There are a ton of examples that I have build over the years on this subject, and the entire project is hosted on CodePlex.com/ScottCateAjax
SideLine: This demo is included in the CodePlex sample as Demo 6F and 6G
It's always funny how the most popular part of a session can not be predicted.
After hours and hours (days and months) of code that I've written and show, the most popular feedback that I've received on my talk was showing Sys.StringBuilder and prototyping it with an appendFormat method.
So it's worthy of a blog post.
Sys.StringBuilder.prototype.appendFormat = Sys$StringBuilder$appendFormat;
function Sys$StringBuilder$appendFormat(mask) {
this.append(String.format.apply(null, arguments));
}
Now you can write code like ....
function BuildResults() {
var sb = new Sys.StringBuilder();
var mask = "Line number {0}<br />";
for (var i = 0; i < 10; i++) {
sb.appendFormat(mask, i);
}
var results = sb.toString();
}
.... and use StringBuilder.appendFormat()
What's interesting about this code, is the apply method called on ....
this.append(String.format.apply(null, arguments));
.... which pushes all the arguments passed into the appendFormat method, on to the String.format call.
Without the use of apply, you're forced to call the method with a hard coded set of parameters. Because the parameters are optional in JavaScript you might be tempted to use the following code ....
function Sys$StringBuilder$appendFormat(mask, arg0, arg1, arg2, arg3, arg4) {
this.append(String.format(mask, arg0, arg1, arg2, arg3, arg4));
}
.... and only support a fixed number of arguments to your appendFormat() method.
Back in 2007, I wrote about this same subject with object inheritance. My goal was to inherit from the Sys.StringBuilder, to create my own string builder, which I then added the appendFormat method to. The natural problem with this approach is that you have to use something other than the built in Sys.StringBuilder.
http://weblogs.asp.net/scottcate/archive/2007/11/28/extending-sys-stringbuilder-with-an-appendformat-method.aspx