Tuesday, July 30, 2013

Combining RESTful, JQuery ,and KnockoutJS

Here's a very easy example of how to join RESTful services with JQuery and some data binding from KnockoutJS.  This is a page that shows the last 100 requested features in the SQL Developer Exchange.




The REST service is very simple as it just strips out a <p> that the editor injects and a little format on the date.


I did this all on jsbin.com so it's nice and easy to share: http://jsbin.com/emadiv/5  The knockoutJS template is the key.  When JSON is returned from the APEX Listener it has a parent node named "items"  The template is bound to the list with this line:

           data-bind="template: { name: 'overview', foreach: items}"

Then for each child under items it will loop and apply the template.  The template is just html inside a script table with the type set to text/html

<!-- Knockout syntax for the template which is the list items -->  
<script id="overview" type="text/html">
<li data-role="list-divider"><!--/ko--></li>
<!-- bind in the link to drill down to the exchange-->
<li> <a data-bind="attr: { href: 'https://apex.oracle.com/pls/apex/f?p=43135:7:0::NO::P7_ID:'+ id }"  alt="">
        <h2>
<!--ko text: title --><!--/ko--></h2>
<span data-bind="text: description"></span>
    </li>
</script>

Then the Javascript which loads the data and applies the template

var requests = "http://apex.oracle.com/pls/apex/dbtools/features/recent";

  // When the page init's go load it up.
$(document).on("pageinit", "#recentRequests", function() {
    $.ajax({
      url: requests ,
      type: "GET",
      success: function (data) {
        // go apply the template to what was retreived
        ko.applyBindings(data, document.getElementById("recentRequests"));
        $('#results').listview('refresh');
      }
    });
});


This barely touches the surface of what can be done with just getting the data out of the database via the APEX Listener.  For example,  the query in this REST is returning 100 rows but pagination is set to 25.  I'll get that hooked up and expand this demo later.  As I tinker with more widgets such as http://www.jqwidgets.com/ I'll write those up also.

Disqus for Kris' Blog