In this installment, I take a VERY quick look at how you can leverage 3rd party JavaScript frameworks like jQuery in your Windows 8 Metro-style applications.
Watch Part 2 video
The biggest change when working with 3rd party frameworks (3PFs) is that you must copy the script files for the framework to the project. This is for two reasons. First, your app has to run when it is not connected to the internet, so you need those files local. Second, external content, even if it is available, runs in a different security context than local code. That difference in security context can cause problems with some 3PFs. If you are working with the project we started in Part 1, you can just add the 3PFs to the js folder, or anywhere else, for that matter. In my case, I added jQuery and jsRender script files to my project’s js folder (see pic at right).
For a simple example, we will use jsRender and jQuery to render the results of a Twitter search on the #Windows8 tag. To get started, replace the code in script.js with the following code:
window.onload = function () {
$('#demoButton').click(doSomething);
};
function doSomething()
{
$.getJSON("http://search.twitter.com/search.json?q=%23Windows8&rpp=20", function (response) {
$('#target').html(
$('#tweetTemplate').render(response.results));
}
As you can see, we are using simple examples. With jQuery, we select the demoButton button and wire up a handler using jQuery’s click function. In the doSomething function we use jQuery’s getJson function to call out to Twitter. We then use jsRender to use an HTML template with the id tweetTemplate to actually show the results inside our target <div>.
The tweetTemplate is shown below:
<script id="tweetTemplate" type="text/x-jsrender">
<div class="tweet">
<div><img src="{{:profile_image_url}}"/><b>{{:from_user_name}} said:</b></div>
<div>{{:text}}</div>
</div>
</script>
Using a 3PFs or WinJS is not a binary choice. You can combine them in whatever way feels most comfortable to you.