<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Jayway Team Blog &#187; ajax</title>
	<atom:link href="http://blog.jayway.com/tag/ajax/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.jayway.com</link>
	<description>Sharing Experience</description>
	<lastBuildDate>Sat, 11 Feb 2012 10:33:02 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Building a Twitter live search app with Knockout, jQuery and ASP.NET MVC 3</title>
		<link>http://blog.jayway.com/2011/07/05/building-a-twitter-live-search-app-with-knockout-jquery-and-asp-net-mvc-3/</link>
		<comments>http://blog.jayway.com/2011/07/05/building-a-twitter-live-search-app-with-knockout-jquery-and-asp-net-mvc-3/#comments</comments>
		<pubDate>Tue, 05 Jul 2011 20:34:52 +0000</pubDate>
		<dc:creator>Anders Fjeldstad</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[knockout]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=8990</guid>
		<description><![CDATA[It’s not trivial to build a well designed web application front-end with the level of responsiveness, performance and features that users expect today. It’s easy to get lost in the boiling mix of jQuery event handlers, HTML markup and AJAX calls, and even a relatively simple GUI can quickly become a nightmare to maintain. One [...]]]></description>
			<content:encoded><![CDATA[<p>It’s not trivial to build a well designed web application front-end with the level of responsiveness, performance and features that users expect today. It’s easy to get lost in the boiling mix of jQuery event handlers, HTML markup and AJAX calls, and even a relatively simple GUI can quickly become a nightmare to maintain.</p>
<p>One way of introducing some structure and order on the client-side is to use a framework like <a href="http://knockoutjs.com/">Knockout</a>. Knockout is a free and open source Javascript library that helps implementing the <a href="http://en.wikipedia.org/wiki/Model_View_ViewModel">Model-View-View Model (MVVM) pattern</a> on the client. It’s well <a href="http://knockoutjs.com/documentation/introduction.html">documented</a> and the official web site is a great starting point with a bunch of <a href="http://knockoutjs.com/examples/">live examples</a> that demonstrate both how to use the built-in features and how to extend it with your own.</p>
<p>In this post, we will see how Knockout can be used together with the mapping plugin, some jQuery and an ASP.NET MVC 3 backend (or model, if you like) to build a simple but effective Twitter “live search” application.</p>
<h2>The goal</h2>
<p>Our objective is simple: the user should be able to input some search critera (like a hashtag or Twitter username), and the application should then present the most recent matching tweets. Also, the result set should be updated automatically by some background procedure on the client so that the GUI always shows that latest matching tweets. (This could be useful when following some live event, for example.) In the end, we would like to end up with something similar to this:</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/07/twitter-live-search.png" rel="lightbox"><img class="alignnone size-full wp-image-9002" title="twitter-live-search" src="http://blog.jayway.com/wordpress/wp-content/uploads/2011/07/twitter-live-search.png" alt="" width="533" height="521" /></a></p>
<p>&nbsp;</p>
<h2>Step 1: Setting up the model</h2>
<p>Twitter exposes a <a href="http://search.twitter.com/api/">search API</a> that is pretty simple to use, and that can respond to search requests in either XML (Atom) or JSON format. We could let our client talk directly to the Twitter API, but in order to be able to improve the application with caching, some fallback if Twitter goes down etc., it’s probably a good idea to build our own model instead - and for that we are going to use a very simple ASP.NET MVC 3 application.</p>
<p>First, create an empty/default web application (with Razor as the chosen view engine) and add a controller - let’s call it <strong>TwitterController</strong>. Then rename the “Index” action that was automatically created with the new controller to “Search”. The controller should look something like this:</p>
<pre class="brush: csharp;">public class TwitterController : Controller
{
    [HttpGet]
    public ActionResult Search()
    {
        return View();
    }
}</pre>
<p>Next, we’re going to create the action method that performs the actual Twitter search. For this lab, we will be using the Atom version of the search API. The request URL is on the format <strong>http://search.twitter.com/search.atom?q=[URL-encoded search parameters]</strong>. Since Atom is XML, we can use LINQ to XML to parse and transform the result set (Twitter <a href="http://search.twitter.com/search.atom?q=knockoutjs">returns a lot of data</a> that we won’t be needing, so we’ll trim it down to a minimum).</p>
<p>But we don’t want to send XML down to the client - we wan’t JSON. Fortunately it’s easy to convert most objects to JSON, and in this case the simplest way is to use the built-in Json method that returns a JsonResult. All this boils down to:</p>
<pre class="brush: csharp;">[HttpPost]
public ActionResult Search(string query)
{
    var atomResult = XDocument.Load(string.Format(
        "http://search.twitter.com/search.atom?q={0}",
        HttpUtility.UrlEncode(query)));
    XNamespace ns = "http://www.w3.org/2005/Atom";
    var searchResult =
        from tweet in atomResult.Descendants(ns + "entry")
        let image = tweet.Elements(ns + "link")
                         .Where(e =&gt; e.Attributes()
                                      .Any(a =&gt; a.Name == "rel" &amp;&amp;
                                                a.Value == "image"))
                         .First().Attribute("href").Value
        let url =   tweet.Elements(ns + "link")
                         .Where(e =&gt; e.Attributes()
                                      .Any(a =&gt; a.Name == "rel" &amp;&amp;
                                                a.Value == "alternate"))
                         .First().Attribute("href").Value
        select new
        {
            id = tweet.Element(ns + "id").Value,
            author = tweet.Element(ns + "author").Element(ns + "name").Value,
            imageUrl = image,
            tweetUrl = url,
            tweetText = tweet.Element(ns + "title").Value
        };
    return Json(searchResult);
}</pre>
<p>(The code above includes some parsing to extract the profile picture of the author and the link to each individual tweet.)</p>
<p>That’s it - we have built our model!</p>
<h2>Step 2: Implementing the view model</h2>
<p>Before we begin building the GUI, we’ll need to add some references to our solution. Either manually or via <a href="http://nuget.org/">NuGet</a>, download jQuery, Knockout and jQuery.tmpl. Then add a “Search.cshtml” view below Views/Twitter (don’t use a “master page” or layout - it’s easier to get an overview of things in a small lab like this if we’re not distributing the solution over too many separate files). Add the mentioned Javascript references. When you’re done, you should have something similar to this:</p>
<pre class="brush: xml;">&lt;!DOCTYPE html&gt;
&lt;html&gt;
    &lt;head&gt;
        &lt;meta charset="utf-8" /&gt;
        &lt;title&gt;Twitter Live Search&lt;/title&gt;
        &lt;script src="@Url.Content("~/Scripts/jquery-1.6.2.js")"
                type="text/javascript"&gt;&lt;/script&gt;
        &lt;script src="@Url.Content("~/Scripts/jquery.tmpl.min.js")"
                type="text/javascript"&gt;&lt;/script&gt;
        &lt;script src="@Url.Content("~/Scripts/knockout-1.2.1.js")"
                type="text/javascript"&gt;&lt;/script&gt;
    &lt;/head&gt;
    &lt;body&gt;
        &lt;!-- TODO --&gt;
    &lt;/body&gt;
&lt;/html&gt;</pre>
<p>Now it’s time to build our view model. The view model contains the client-side application logic, if you like - it defines what the application can do and what properties it has, without directly referencing any markup or DOM elements.</p>
<p>The view model for this lab is very simple - it so far contains two properties and a method, used to store the current search query, the matching tweets and to perform a search against the model, respectively. It could look like this:</p>
<pre class="brush: js;">&lt;script type="text/javascript"&gt;
    function SearchViewModel() {
        this.query = ko.observable('');
        this.tweets = ko.observableArray();
    }

    SearchViewModel.prototype.search = function () {
        var q = this.query();
        if (q.length &gt; 0) {
            $.ajax({
                type: 'POST',
                url: '/Twitter/Search',
                data: { query: q },
                dataType: 'json',
                success: function (data) {
                    // TODO
                }.bind(this)
            });
        } else {
            // TODO
        }
    };
&lt;/script&gt;</pre>
<p>Not that much going on here; the query and tweets properties are empty initially, and the search method uses jQuery to post an AJAX request to our model on the server and retrieve the result as a JSON object (array of tweets).</p>
<p>How should we implement the “success” handler in the search method? We could clear the tweets array and add the new search results. But remember that we want to receive “updates” to our search results continuously - then ideally we would like to just add new tweets (and remove old ones), not replace the entire collection.</p>
<p>This is a great possibility to try out the <a href="http://knockoutjs.com/documentation/plugins-mapping.html">Mapping plugin for Knockout</a>. Once we’ve downloaded it and added the script reference, it enables us to implement the success handler of the AJAX request like this:</p>
<pre class="brush: js;">success: function (data) {
    ko.mapping.updateFromJS(this.tweets, data);
}.bind(this)</pre>
<p>And then to set up a “<a href="http://knockoutjs.com/documentation/plugins-mapping.html#uniquely_identifying_objects_using_keys">key definition</a>” for the tweets collection (which is used by Mapping to determine which items should be added, updated and removed), we just modify our constructor slightly:</p>
<pre class="brush: js; highlight: [3,4,5,6,7];">function SearchViewModel() {
    this.query = ko.observable('');
    this.tweets = ko.mapping.fromJS(
        [],
        {
            key: function (tweet) { return ko.utils.unwrapObservable(tweet.id) }
        });
}</pre>
<p>Note that we’re defining the key of the tweets collection to be the ID value that Twitter so conveniently provides. If you want more information about the Mapping plugin, the official Knockout site is a good resource.</p>
<p>Next: implementing the auto-refresh feature. Whenever a search query is present, the matching tweets should be updated every, say, three seconds to reflect changes in the model. One way of accomplishing this is to have the success callback of the AJAX search request call the search method recursively, with a delay. The <strong>complete view model</strong> then looks like this:</p>
<pre class="brush: js; highlight: [9,13,14,15,16,17];">&lt;script type="text/javascript"&gt;
    function SearchViewModel() {
        this.query = ko.observable('');
        this.tweets = ko.mapping.fromJS(
            [],
            {
                key: function (tweet) { return ko.utils.unwrapObservable(tweet.id) }
            });
        this.autoRefreshId = null;
    }

    SearchViewModel.prototype.search = function () {
        var timeoutId = this.autoRefreshId;
        if (timeoutId) {
            window.clearTimeout(timeoutId);
            this.autoRefreshId = null;
        }
        var q = this.query();
        if (q.length &gt; 0) {
            $.ajax({
                type: 'POST',
                url: '/Twitter/Search',
                data: { query: q },
                dataType: 'json',
                success: function (data) {
                    ko.mapping.updateFromJS(this.tweets, data);
                    this.autoRefreshId = window.setTimeout(
                        this.search.bind(this), 3000);
                }.bind(this)
            });
        } else {
            ko.mapping.updateFromJS(this.tweets, []);
        }
    };
&lt;/script&gt;</pre>
<p>(I’ve added a couple of lines to disable the auto-refresh when the search box is empty, plus a check that disables any pending search when the user performs a new one. Also, the search results are emptied when a search is performed with an empty query.)</p>
<h2>Step 3: Designing the view</h2>
<p>To keep things clean and simple, the view will consist only of a search box and a list of tweets. We want to achieve something along this line:</p>
<pre class="brush: xml;">&lt;form&gt;
    &lt;input type="search" placeholder="Input #hashtag, @@username or something else" autofocus /&gt;
    &lt;input type="submit" value="Search" /&gt;
&lt;/form&gt;

&lt;ul id="tweets"&gt;
    &lt;li&gt;
        &lt;a href="[url-of-tweet]" title="[author-name]"&gt;
            &lt;img src="[url-of-author-image]" alt="[author-name]" /&gt;
        &lt;/a&gt;
        &lt;h6&gt;[author-name]&lt;/h6&gt;
        &lt;p&gt;[tweet-text]&lt;/p&gt;
    &lt;/li&gt;
    &lt;!-- More tweets... --&gt;
&lt;/ul&gt;</pre>
<p>Let’s also add some declarative Knockout data bindings that tie the view to the view model. If we modify the <strong>search form</strong> just a bit...</p>
<pre class="brush: xml;">&lt;form data-bind="submit: search"&gt;
    &lt;input type="search" data-bind="value: query, valueUpdate: 'afterkeydown'" placeholder="Input #hashtag, @@username or something else" autofocus /&gt;
    &lt;input type="submit" value="Search" /&gt;
&lt;/form&gt;</pre>
<p>...Knockout will update the query property of the view model automatically when the user changes the text in the search box, and a search will be performed whenever the user presses the Enter key inside the search box.</p>
<p>What about the <strong>search results</strong>? A perfect scenario for using the Knockout <a href="http://knockoutjs.com/documentation/template-binding.html">template binding</a>! First, create a template for how a single tweet should look like:</p>
<pre class="brush: xml;">&lt;script id="tweetTemplate" type="text/html"&gt;
    &lt;li data-bind="attr: { id: id }"&gt;
        &lt;a data-bind="attr: { href: tweetUrl, title: author }"&gt;
            &lt;img data-bind="attr: { src: imageUrl, alt: author }" /&gt;
        &lt;/a&gt;
        &lt;h6 data-bind="text: author"&gt;&lt;/h6&gt;
        &lt;p data-bind="text: tweetText"&gt;&lt;/p&gt;
    &lt;/li&gt;
&lt;/script&gt;</pre>
<p>Then data-bind the HTML list against the tweets property of the view model, specifying our template as the way to render each item. It’s really easy:</p>
<pre class="brush: xml;">&lt;ul id="tweets"
    data-bind="template: {
                   name: 'tweetTemplate',
                   foreach: tweets
               }, visible: tweets().length &gt; 0"&gt;&lt;/ul&gt;</pre>
<p>(Note that the list won’t be visible at all when the view model contains no tweets.)</p>
<p><strong>Bonus:</strong> Add an animation that is used when new tweets are added to the list, using the afterAdd option of the template binding:</p>
<pre class="brush: xml; highlight: [5,6,7];">&lt;ul id="tweets"
    data-bind="template: {
                   name: 'tweetTemplate',
                   foreach: tweets,
                   afterAdd: function (element) {
                       $(element).hide().fadeIn('fast');
                   }
               }, visible: tweets().length &gt; 0"&gt;&lt;/ul&gt;</pre>
<p>At this point only one thing remains: some boostrapping logic. When the DOM has loaded, we need to create an instance of our view model and tell Knockout to connect the bindings to it. One line of code within the jQuery “document ready” event handler:</p>
<pre class="brush: js; highlight: [3];">&lt;script type="text/javascript"&gt;
    $(function () {
        ko.applyBindings(new SearchViewModel());
    });
&lt;/script&gt;</pre>
<p><strong>And we’re done!</strong> Verified on my Windows 7 machine in Chrome 12, Internet Explorer 9 and Firefox 5. Here’s the complete solution (where I’ve added some CSS to make it look less horrible): <strong><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2011/07/TwitterLiveSearchLab1.zip">TwitterLiveSearchLab.zip</a></strong></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/07/05/building-a-twitter-live-search-app-with-knockout-jquery-and-asp-net-mvc-3/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Wicket Javascript Internals dissected</title>
		<link>http://blog.jayway.com/2008/09/26/wicket-javascript-internals-dissected/</link>
		<comments>http://blog.jayway.com/2008/09/26/wicket-javascript-internals-dissected/#comments</comments>
		<pubDate>Fri, 26 Sep 2008 13:20:25 +0000</pubDate>
		<dc:creator>Nino Martinez</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[frameworks]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[open source]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[web]]></category>
		<category><![CDATA[wicket]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=290</guid>
		<description><![CDATA[SO you need to do something special with a javascript and you want to integrate that with wicket. In my last article I looked at this from the wicket side and wrote about what you can do to push something out from wicket. But what if you want to interact? Then you will have to take a peek at wickets javascript internals. If you are working on an ajax component you get these wicket javascript source files included as default [...]]]></description>
			<content:encoded><![CDATA[<p>SO you need to do something special with a javascript and you want to integrate that with wicket. In my <a href="http://ninomartinez.wordpress.com/2008/09/09/apache-wicket-javascript-integration/">last article</a> I looked at this from the wicket side and wrote about what you can do to push something out from wicket. But what if you want to interact? Then you will have to take a peek at wickets javascript internals. If you are working on an ajax component you get these wicket javascript source files included as default:</p>
<ol>
<li>wicket-event.js</li>
<li>wicket-ajax.js</li>
</ol>
<h3>wicket-event.js</h3>
<p>This file contains everything Wicket needs for event handling, but also methods for detecting browser like Wicket.Browser.isIELessThan7() which could come in handy if youre doing your own script, no need to write it again.. </p>
<h3>wicket-ajax.js</h3>
<p>This file hold everything Wicket needs for doing ajax. So it's a big file containing a lot of interesting possibilities.</p>
<p>The most interesting method are wicketAjaxGet its the way to contact the server doing ajax. It's signature are this:</p>
<pre class="javascript">&nbsp;
<span style="color: #003366; font-weight: bold;">function</span> wicketAjaxGet<span style="color: #66cc66;">&#40;</span>url, successHandler, failureHandler, precondition, channel<span style="color: #66cc66;">&#41;</span>
&nbsp;</pre>
<p>The first parameter are the url for wicketAjaxGet to call server side with, it usually gets generated from serverside, and you can add parameters to it and get them server side. Furthermore it takes 3 functions and a channel. Channel are also usually populated for you so dont think about that. The functions however are called either on sucess, failure or as a precondition. These supply very nice options for you if you need to do something special with the result of the wicketAjaxGet you can put in callbacks. Small example from the mooTip ajax integration:</p>
<pre class="javascript">&nbsp;
<span style="color: #003366; font-weight: bold;">function</span> mootipAjaxtooltip022<span style="color: #66cc66;">&#40;</span>callback<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
<span style="color: #003366; font-weight: bold;">var</span> content=<span style="color: #3366CC;">''</span>;wicketAjaxGet<span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">'?wicket:interface=:0:tooltip02::IBehaviorListener:1:'</span>,
 <span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
 <span style="color: #003366; font-weight: bold;">var</span> tip=document.<span style="color: #006600;">getElementById</span><span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">'mooTipContent'</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">innerHTML</span>;
 <span style="color: #003366; font-weight: bold;">var</span> callbackInside=callback;
 <span style="color: #003366; font-weight: bold;">var</span> runCallback=  callbackInside.<span style="color: #006600;">pass</span><span style="color: #66cc66;">&#40;</span>tip<span style="color: #66cc66;">&#41;</span>;
 runCallback<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
  <span style="color: #66cc66;">&#125;</span>
, <span style="color: #003366; font-weight: bold;">null</span>,<span style="color: #003366; font-weight: bold;">null</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>As you can see, if you count the parameters, I put in a success method for wicket to call once the request has finished, in this case it sets up a tooltip and displays it, by a method thats passed along using the content of the dom element called 'mooTipContent'.</p>
<p>Theres also lighter methods like for example wicketHide and wicketshow. Methods for manipulating visibility of dom objects. Theres many more functions in there. But these should get you going.</p>
<h3>The complete package</h3>
<p>A small example that shows a invisible veil when a abstractajaxTimerEventBehavior is called:</p>
<pre class="javascript">&nbsp;
css/html:
#veil<span style="color: #66cc66;">&#123;</span>
position:absolute;top:<span style="color: #CC0000;">0</span>;left:<span style="color: #CC0000;">0</span>;
 width:<span style="color: #CC0000;">100</span>%;height:<span style="color: #CC0000;">100</span>%;
 z-index: <span style="color: #CC0000;">99</span>;
 <span style="color: #009900; font-style: italic;">/*cursor: wait;*/</span>
 <span style="color: #66cc66;">&#125;</span>
&lt;<span style="color: #3366CC;">&quot;p id=&quot;</span>veil<span style="color: #3366CC;">&quot; style='display: none;' &quot;</span>&gt;&lt;<span style="color: #3366CC;">&quot;/p&quot;</span>&gt;
Java:
		AbstractAjaxTimerBehavior ajaxTimerBehavior = <span style="color: #003366; font-weight: bold;">new</span> AbstractAjaxTimerBehavior<span style="color: #66cc66;">&#40;</span>
				Duration.<span style="color: #006600;">seconds</span><span style="color: #66cc66;">&#40;</span><span style="color: #CC0000;">1</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
			@Override
			<span style="color: #003366; font-weight: bold;">protected</span> CharSequence getCallbackScript<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
				<span style="color: #009900; font-style: italic;">// TODO Auto-generated method stub</span>
				<span style="color: #000066; font-weight: bold;">return</span> <span style="color: #3366CC;">&quot;wicketShow('veil');&quot;</span> + <span style="color: #003366; font-weight: bold;">super</span>.<span style="color: #006600;">getCallbackScript</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
			<span style="color: #66cc66;">&#125;</span>
&nbsp;
			@Override
			<span style="color: #003366; font-weight: bold;">protected</span> CharSequence getSuccessScript<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
				<span style="color: #009900; font-style: italic;">// TODO Auto-generated method stub</span>
				<span style="color: #000066; font-weight: bold;">return</span> <span style="color: #3366CC;">&quot;wicketHide('veil');&quot;</span> + <span style="color: #003366; font-weight: bold;">super</span>.<span style="color: #006600;">getSuccessScript</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
			<span style="color: #66cc66;">&#125;</span>
....
&nbsp;</pre>
<p>And thats it, now you should be ready to do your own stuff <img src='http://blog.jayway.com/wordpress/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2008/09/26/wicket-javascript-internals-dissected/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

