Script# - Literal feature... How did I miss this one?

Today, I’m doing some work with Script# and I ran into the one thing about Script# that I don’t like: there are a few areas where Script# just isn’t able to perform some task. This happens a lot when you are developing Atlas (MS Ajax) components instead of using Nikhil’s ScriptFX client library.

Today I ran into one of those areas. Specifically I needed to dynamically add/remove options from a select element. In JS this is a breeze for me, but Script#'s SelectElement’s options array is defined as a dictionary which doesn’t allow for adding elements. In the process of doing it I ran across an article on how to do it in a more DOM-compliant manner (read that as "the standard way you’re supposed to do it"). The article is over here.

Anyway, I originally used Script.Eval, but I knew that was going to put some ugly code in my resulting Javascript files (I really do hate that).

While I was doing that I noticed the reference to "Script.Literal" in my intellisense, so I grabbed the docs and took a look. To my amazement this new element did away with this limitation once and for all.

Here’s what it does. It lets you emit your own script code into the resulting script. So I could use the above article and reference properties that don’t exist in the Script# implementation. That really rocks!

So you could do something like this:

// Hide all elements of a certain type in my doc and hide them 
// (this is a contrived example, I know)
public void HideAllElementsOfType(string tagName)
{
   Script.Literal("$(tagName).css('display', 'none')"); // this is a JQuery call
}

In the resulting JS there will be something like this (I’m manually doing this so it won’t be exact here):

function hideAllElementsOfType(tagName)
{
    $(tagName).css('display', 'none');
}

You see? it took the string in the literal and injected it into the source. Using a "$" is not possible with Script#/C#, but we were able to inject it into our code with no problems.  Literal also supports String.Format syntax as well. This is so cool! It means that it is trivial to get around Script# limitations and still get good performance (no need to litter your code with Eval)

Print | posted on Wednesday, December 10, 2008 3:41 PM

Feedback

No comments posted yet.
Title  
Name
Email (never displayed)
Url
Comments   
Please add 3 and 5 and type the answer here:
div>