Using getElementsBySelector in ScriptSharp

I’m on my way to my second spike for one of my clients on playing with ScriptSharp to extend Rasta with Ajax functionality, and really wanted to be able to select elements as I would in CSS, using selectors (something I got quite used to with jQuery).

ScriptSharp comes with various assemblies you can link to. The one called sscorlib is a .net mapping over a javascript library that extends document to have a getElementsBySelector method. But for some reason, ScriptSharp doesn’t map that method.

So how do you call random code in ScriptSharp without resorting to evil eval code? You create a function of course! Here’s the snippet.

        public static DOMElement[] GetElementsBySelector(string selector, DOMElement root)

        {

            return new Function("return document.getElementsBySelector(selector, arg);", "selector", "arg")

                .Call(Document.DocumentElement, selector, root) as DOMElement[];

        }

We define a function that calls the correct javascript code, declare the argument names we will pass it, and finally call it by passing our selector and the root.

In one word, sweet.

Ads

Comment