Extending Adam.JSGenerator in your application

We’re working on adding better support for jQuery and JQuery UI in the next version of the Adam.JSGenerator library, but there’s nothing that keeps you from adding your extensions to make your expressions more readable and maintainable.

For example, if we were to want support for a particular jQuery UI function today, it’s simply a matter of adding an extension method to your application, since most jQuery and jQuery UI functions are calls on a jQuery object, that can come from any sort of expression, be it a call to jQuery itself, a set stored in a variable, passed as a parameter, or the result of another jQuery/jQuery UI call (called chaining).

So what do we do?

First, we make a new static class. The name of this class doesn’t really matter, because we’ll be writing extension methods, but it’s nice to give it a helpful name and anything ending in “Helpers” seems to be the convention nowadays. So we could name this class JQueryUIHelpers:

C#
1
2
3
static class JQueryUIHelpers
{
}

Then, we write our extension method. An extension method is simply a static method in a static class with an extra keyword added to the first argument. This will let us call the extension method using a different syntax, and make it appear as if it’s a call on an object. Make no mistake, though, because it’s simply syntactic sugar.

In order for our extension method to work correctly, our first argument needs to be of type Expression and adorned with the ‘this’ modifier:

C#
1
2
3
public static CallOperationExpression Accordeon(this Expression source, object options)
{
}

As you can see, I’ve chosen the second argument to be a simple object. This is so I can accept any type to be passed as options to the accordeon() function. A lot of jQuery and jQuery UI functions accept a simple object to specify options, and this way I can use anonymous types. We return a CallOperationExpression for good form. Then it’s simply a matter of implementing the method:

C#
1
return source.Dot("accordeon").Call(Expression.FromObject(options));

Calling this new extension method is pretty straightforward. You only need to make sure that the static class is “visible” to where you call it, so you may have to add a “using” statement to the top.

C#
1
var call = JS.JQuery("#container").Accordeon(new {collapsible = true});

And that’s how it’s done.

As you can see, it makes our generation code a bit more readable. Your mileage may vary, of course. If you have a number of functions or that you use all over, and they’re calls on jQuery objects through jQuery or any sort of plugin you wrote, this might be a technique you could use to simplify things.

As always, feedback is welcome.

Sample Code

The article contains sample code project(s).
You must be logged in to view or download sample code.
Sign in now

Comments

Leave a comment
You must be logged in to post comments.
Sign in now
 
 
Technical
Business
rss feed