Go Back

Introducing jLight – Talking to the DOM using Silverlight and jQuery.

Introduction

With the recent news about Silverlight on the Windows Phone and all the great Out-Of-Browser features in the upcoming Silverlight 4 you almost forget Silverlight is a browser plugin. It most often runs in a web browser and often as a control. In many cases you need to communicate with the browser to get information about textboxes, events or details about the browser itself. To do this you can use JavaScript from Silverlight. Although Silverlight works the same on every browser, JavaScript does not and it won’t be long before problems arise. To overcome differences in browser I like to use jQuery. The only downside of doing this is that there’s a lot more code needed that you would normally use when you write jQuery in JavaScript.

Lately, I had to catch changes is the browser scrollbar and act to the new position. I also had to move the scrollbar when the user dragged around in the Silverlight application. With jQuery it was peanuts to get and set the right attributes, but I found that I had to write a lot of code on Silverlight side.  With a few refactoring I had a separated out the plumbing into a new class and could call only a few methods on that to get the same thing done. The idea for jLight was born.

jLight vs. jQuery

The main purpose of jLight is to take the ease of use of jQuery and bring it into Silverlight for handling DOM interaction. For example, to change the text color of a DIV to red, in jQuery you would write:

jQuery("div").css("color","red");

In jLight the same thing looks like so:

jQuery.Select("div").Css("color","red");

 

Another example. To change the offset in of the last SPAN you could write this in jQuery :

jQuery("span:last").offset({left : 10, top : 100}); 
 

In jLight this would do the same:

jQuery.Select("span:last").Offset(new {left = 10, top = 100 }); 

 

Callbacks

Nothing too special so far. To get the same thing done using the “normal” HtmlPage.Window.Eval, it wouldn’t require too much effort. But to wire up a handler for events from the browser it’s a whole different story. Normally you need to register ScriptMembers, ScriptableTypes or write some code in JavaScript. jLight takes care of the plumbing and provide you with an simple interface in the same way jQuery would.

If you would like to handle the scroll event of the BODY of your html page, you’ll have to bind the event using jQuery and have a function call back to a registered function in Silverlight. In the example below I assume there’s a method “SomeMethod” and it is registered as a ScriptableObject as “RegisteredFromSilverlight” from Silverlight.

 

jQuery("body:first").scroll(function()
{    
    var sl = document.getElementbyId("SilverlightControl");
    sl.content.RegisteredFromSilverlight.SomeMethod($(this));
});

 

 

 

Using jLight  in Silverlight the code would be even simpler. The registration of RegisteredFromSilverlight  as ScriptableObject can be omitted.  Besides that, you don’t have to write any JavaScript or evaluate strings with JavaScript.

 

jQuery.Select("body:first").scroll(SomeMethod);

 

Lambdas

Using a lambda in Silverlight can make it even simpler.  Each is the jQuery equivalent of foreach in C#. It calls a function for every element found by jQuery. In this example all INPUT elements of the text type are selected. The FromObject method is used to create a jQueryObject from an object containing a ScriptObject. The Val method from jQuery is used to get the value of the INPUT elements.

 

jQuery.Select("input:text").Each((element, index) =>
    {
        textBox1.Text += jQueryObject.FromObject(element).Val();
        return null;
     });

 

Ajax

One thing jQuery is often used for is making Ajax calls. Making calls to services to external services can be done from Silverlight, but as easy as using jQuery. As an example I would like to show how jLight does this. Below is the entire code behind. It searches my name on twitter and shows the result. This example can be found in the source of the project. The GetJson method passes a Silverlight JsonValue to a callback. This callback instantiates Twit objects and adds them to a ListBox called TwitList.

 

public partial class DemoPage2 : UserControl
{
    public DemoPage2()
    {
        InitializeComponent();
        jQuery.Load();
    }
 
    private void CallButton_Click(object sender, RoutedEventArgs e)
    {
        jQuery.GetJson("http://search.twitter.com/search.json?lang=en&q=sorskoot",
                       Done);
    }
 
    private void Done(JsonValue arg)
    {
        var tweets = new List<Twit>();
        foreach (JsonObject result in arg["results"])
        {
            tweets.Add(new Twit()
                   {
                       Text = (string)result["text"],
                       Image = (string)result["profile_image_url"],
                       User = (string)result["from_user"]
                   }
            );
        }
        TwitList.ItemsSource = tweets;
    }
}
 
public class Twit
{
    public string User { get; set; }
    public string Image { get; set; }
    public string Text { get; set; }
}

 

Conclusion

Although jLight is still in development it can be used already.There isn’t much documentation yet, but if you know jQuery jLight isn’t very hard to use.  If you would like to try it, please let me know what you think and report any problems you run in to.

jLight can be found at:

 

http://jlight.codeplex.com

jLightLogo

Facebook Twitter DZone It! Digg It! StumbleUpon Technorati Del.icio.us NewsVine Reddit Blinklist Add diigo bookmark

Comments  12

  • rolex daytona 19 okt

    When you are looking for that perfect gift to get for the special man in your life, you can never go wrong with designer mens watches. The rolex daytona and the rolex submariner fall into the professional line of watches. As one of the most prestigious watch brands in the world, hublot watches is specialized in splendid timepieces. panerai watches aren't the most well known of men's watches but this esoteric brand is becoming highly desirable among men. breitling watches have made an excellent name for themselves. If there are any watches that should be known for all the watch collectors, breitling navitimer should be among one of them. So far as we know, iwc watches are one of the most famous brand watches in the world. Also, tag heuer watches and chopard watches maybe your choice. omega seamaster watch and its tryst as an eternal timepiece began in the year 1948.
  • rolex daytona 19 okt

    As we all know, uggs Boots Shoes from Australia are made from merino lambskin in double layers.Its function in repelling moisture and coldness is even incredible.If you want to buy it,you can find ugg online through the internet.This quick guide will get you set up and on your way to finding cheap Uggs at ugg outlet prices! Because there are so many ugg website online.You can also check for prices at the more popular auction websites such as Ebay,there must be a name of ugg ebay or ugg.com.You can find many kind of ugg Boots Shoes,such as ugg nightfall bootsugg tall bootsugg butte bootugg suede boots and ugg ultra and so on.
  • rolex daytona 19 okt

    As everybody known, rolex watches are some of the famous watches in the world. But they are very expensive. rolex replica watches are more and more popular now. rolex mens watches have the best selling point. The rolex Submariner and the rolex Deepsea are two of the truly exceptional sport models Rolex makes. rolex Perpetual and rolex Daytona are also the two types have special appearance and manufacture. Released in the year 1945, to mark the 40-year anniversary of the inception of Rolex, the rolex Datejust is the best selling watch of Rolex. rolex Air king is famous for its high quality and elegant appearance.
  • rolex daytona 19 okt

    Nowadays replica watches are becoming more and more popular in the market. rolex watches are known for both their precision and elegance such as rolex air king watches, rolex submariner watches and rolex datejust watches. breguet watches are among the extremely unique and sophisticated timepieces. blancpain watches are works of excellence and decadence. bell ross watches may be well characterized by the squared military-style instrument face. With excellent craftsmanship and elegant style, Baume Mercier watches have get great value in Swiss watchmaking. bvlgari watches are noted for their fashion and precision, which make them well received in the world luxury industry. If you want to accentuate your beauty and style with good-looking accessories, chopard watches are no doubt your ideal options. dewitt watches and montblanc watches are well known brands of watches all over the world, too. oris watches are greatly sought after in the realm of luxury watches. panerai watchess are very beautiful. Their large, chunky lines are subdued by their understated styling. patek philippe watches are admired for their intricate craftsmanship and super technical advance. piaget watches are a status symbol for wealth, fortune, and prestige. If you intend to give something very special this season to people who are close to you then choose to buy rado watches. As one of the most popular timepieces in the world, tudor watches are well received by their splendid design and great durability. u boat watches is a highly elite watch brand that was founded by Italian watch maker Italo Fontana. ebel watches share the same properties with the world's most spectacular architecture in innovation, melodious and the most talented craftsmanship. ferrari watches and franck muller watches are famous for its high quality and elegant appearance. Self-producing movement is the representative of glashutte watches. gucci watches have been around since 1920 and have been leading the time peace market for many decades now. hermes watches were well received since they were first launched into the market. As one of the most prestigious watch brands in the world, hublot watches are specialized in splendid timepieces. louis vuitton watches and maurice lacroix watches maybe your best choice.
  • rolex daytona 19 okt

    Everyone knows that swiss replica watches are the finest quality timepieces in the world. panerai watches’ great popularity is based on its high-end timepieces with high quality and top craftsmanship. One prominent feature of Hublot watches that makes the brand different from other luxury watch brands lies in the materials used in manufacturing. Also, tag heuer watches and Chopard watches are people’s choice. If there are any watches that should be known for all the watch collectors, breitling Navitimer should be among one of them. The srolex DateJust, rolex Daytona and the rolex Submariner fall into the professional line of watches. As a world known leading luxury brand, burberry watches are considered as a symbol of classic style and elegance. breguet watches have a history of more than 230 years through the arrangement of spare parts. As one of the most sought after watches in the world, patek philippe watcheshas literally stood the test of time. And Audemars Piguet watches are some of the world's best built timepieces. U Boat watches are characterized as bold, aggressive and oversized and Franck Muller watches are complex, innovative. If you are looking for a watch of high quality and superior elegance, I think B R M watches will be your choice. A Lange Sohne watches and Ferrari watches are two famous brands in the world, too.
  • Namari 26 apr

    Good point. I hadn't thuohgt about it quite that way. :)
  • ughkiqrddne 28 apr

    HYfZNW , [url=http://fnolqsdkpeez.com/]fnolqsdkpeez[/url], [link=http://dwcavqyoadkk.com/]dwcavqyoadkk[/link], http://laotaupkbixe.com/
  • hhwcuyuimkv 30 apr

    U3XjVd , [url=http://yucgkfoyyexl.com/]yucgkfoyyexl[/url], [link=http://dcsytbqrnkpd.com/]dcsytbqrnkpd[/link], http://sfsiklwhqnda.com/
  • Roberta 15 jul

    Walking in the presence of giants here. Cool thinking all aruond!
  • sasbehhxnh 16 jul

    8lDjkd , [url=http://wkhrgcohwnwl.com/]wkhrgcohwnwl[/url], [link=http://oxbyevqdmdev.com/]oxbyevqdmdev[/link], http://rlwivhwnkiol.com/
  • sasbehhxnh 16 jul

    8lDjkd , [url=http://wkhrgcohwnwl.com/]wkhrgcohwnwl[/url], [link=http://oxbyevqdmdev.com/]oxbyevqdmdev[/link], http://rlwivhwnkiol.com/
  • upmjouiewc 20 jul

    4l7yvn , [url=http://srioyfxzouuo.com/]srioyfxzouuo[/url], [link=http://hyejqdzmamos.com/]hyejqdzmamos[/link], http://gjgaixufldyp.com/
Post a comment!
  1. Formatting options