Sunday, September 28, 2008

JQuery and MonoRail

Over the weekend, I made the move from RC3 of Monorail (http://castleproject.org) to the Trunk of Monorail targeting .Net 2.0.

I took this opportunity because, Ayende (http://ayende.com/blog/) released some code on the Castle project mailing list as well as being added to the Trunk that helps people who prefer JQuery as one of their Javascript library. Ayende shared a JQueryGenerator class and a JQueryElementGenerator class.

Side Note to avoid conflicts with other javascript libraries add this to you layout template wrapped in the script tag:
<script type="text/javascript">
{
var jQuery = jQuery.noConflict();
});
</script>




I starting using them and created a few personal Unit test classes to test them. These test classes at the moment do not have full coverage, but they are a start.
When targeting the .Net 2.0 framework I ran into an issue with JSGeneratorDispatcher when it called a the hide method on JSQueryGenerator class. The resolution ended up being to add a params attribute to the method signature of methods that have an array in the signature. (Important: This is now patched in the trunk)
For example changing:
public override void Hide(string[] ids)
{
SelectRelevantElements(ids);
CodeGenerator.Write(".hide();");
}
To:
public override void Hide(params string[] ids)
{
SelectRelevantElements(ids);
CodeGenerator.Write(".hide();");
}

Steps to use JQuery in MonoRail

I recommend:

1) Either commenting out the other javascript libraries referenced in your layout view, or adding an alias for JQuery and wrap this in script tag.
<script type="text/javascript">
{
var jQuery = jQuery.noConflict();
});
</script>

2) Add JQuery to you layout:
<script type="text/javascript" src="$siteroot/content/js/jquery-1.2.6.js"> </script>

3) Use the latest Monorail source code from the Trunk, to take advantage of Javascript Generation using JQuery as you default.
Update global.asax.cs , add :
using Castle.MonoRail.Framework.JSGeneration;
using Castle.MonoRail.Framework.JSGeneration.jQuery;


also add method To Your Global.asax:
public void Configure(IMonoRailConfiguration config)
{


config.JSGeneratorConfiguration.AddLibrary("jquery-1.2.6", typeof(JQueryGenerator))
.AddExtension(typeof(CommonJSExtension))
.SetAsDefault();

}


3) Create yourself a helper class for JQuery to make it easier to create Ajax calls, etc. via JQuery.

1 comment:

  1. and you can also skip JS generation altogether and just use the jQuery api directly :)

    ReplyDelete