Blog Archives

ko.datasource–Enable simple binding to remote data sources

When using Knockout, we often want to bind to data that is retrieved from an AJAX request. In addition, it is not always efficient to populate the entire view model when the page loads. When adding paging, sorting and filtering of our data into the mix, if we’re not careful we can end up with a lot of accidental complexity and code duplication on our hands. To avoid that happening, I’ve created a small plugin for Knockout that makes interacting with remote datasources simple. Lets take a look.

The Bindings

I want my knockout bindings to be as simple as possible. Regardless of where I get my data, my view should be written as if it were completely unaware of where the data came from. In that vain, our markup should be the same as if we were binding to a standard knockout observable or observable array.

Let’s assume we want to display some data in a table. Our markup might look like this:

<table>
    <
thead
>
        <
tr
>
            <
th>Id</th
>
            <
th>Name</th
>
            <
th>Sales</th
>
            <
th>Price</th
>
        </
tr
>
    </
thead
>
    <
tbody data-bind="foreach: items"
>
        <
tr
>
            <
td data-bind="text: id"></td
>
            <
td data-bind="text: name"></td
>
            <
td data-bind="text: sales"></td
>
            <
td data-bind="text: price"></td
>
        </
tr
>
    </
tbody
>           
</
table>

Nothing too complicated, or unexpected. Just the basic foreach and text bindings.

Of course since we might expect a fair few results, we wish to paginate our data. Let’s add some simple bindings for this too.

<span id="pager">
    <
button data-bind="click: items.pager.first">First</button
>
    <
button data-bind="click: items.pager.previous">Prev</button
>
    <
span class="summary"
>Page 
        <
span data-bind="text: items.pager.page"></span
> of 
        <
span data-bind="text: items.pager.totalPages"></span></span
>
    <
button data-bind="click: items.pager.next">Next</button
>
    <
button data-bind="click: items.pager.last">Last</button
>
</
span>

Again, nothing too drastic – some simple buttons for pagination and an indication of what page we’re on. Do note however that we’re binding to a pager attached to the items. More on that in a moment.

The view model

The model is where the magic happens, it’s where any rich interactions will be specified. To keep our models DRY however, we probably don’t want to specify things like pagination in every view model we create. With the ko.datasource plugin, we can keep things simple:

var viewModel = {
   
items: ko.observableArray([]).extend
({
        //getAnimals is a data service to populate the viewmodel

       
datasource: getAnimals
,
       
pager
: {
           
limit: 3
        }
    })
};

We have an observableArray of items, just as if we were working with data in-memory, but two extenders have been applied to the array -  a datasource and a pager.

The datasource extender takes a single parameter; a function that will call into our remote data source. This function could, for example, use the ajax librarys of jQuery to call a webservice. We’ll take a deeper look at this in a second.

The pager extender takes a single parameter also; an object indicating how many items we would like to see per page. It will also attach itself to our observable array to expose additional pagination properties and methods. This is what the pager in our view is bound to.

The remote call

As previously mentioned, we can use our favorite library to call into whatever remote datasource we want. Let’s say we’re using jQuery’s ajax API:

function getAnimals() {
   
$.ajax
({
       
type: ‘GET’
,
       
url: ‘/my/remote/endpoint/’
,
       
data
: {
           
limit: this.pager.limit
(),
           
startIndex: this.pager.limit() * ( this.pager.page()1
)
        },
       
context: this
,
       
success: function( data
) {
           
this( data.rows
);
           
this.pager.totalCount( data.count )
;
        },
       
dataType: ‘json’
    });
};

The datasource (the extended observable array) is set as the context of the this keyword and that means we have access to the pager options. When data is successfully retrieved from our AJAX call, we can replace the data in our datasource by writing to the observable:

var observableArray = this;
observableArray(data.rows);
//or just
this(data.rows);

Additionally, since we’re using a pager, we should tell the pager how many results the server has in total so that it can figure out how many pages there are:

this.pager.totalCount( data.count );

An important thing to note is that the function we use here will behave like a computed observable, that is, it will run automatically whenever any of its dependencies change. This means that as our pager changes page, or when the row limit (records per page) changes, the remote call will be reevaluated in order to fetch the new data to show. This also means that if we pass dependencies from our viewModel as parameters to the remote call, they will also cause the datasource to be updated if they change. This is very handy as we can also use this feature for additional server-side filtering if needed.

That’s it!

Seriously, that’s all you need. Our datasource will evaluate when the view is first bound to it, and then will be reevaluated whenever our remote calls’ dependencies change.

Check out a live example here:  http://jsfiddle.net/craigcav/UzUBm/

And download the source here: https://github.com/CraigCav/ko.datasource

Enjoy.

Acknowledgements

None of this would’ve been possible without the inspiring work Ryan Niemeyer put into documenting KnockoutJS on his blog. In particular without the following two posts, this plugin probably wouldn’t exist.

http://www.knockmeout.net/2011/04/pausing-notifications-in-knockoutjs.html

http://www.knockmeout.net/2011/06/lazy-loading-observable-in-knockoutjs.html

Advertisements

Binding multiple event handlers to JqGrid

[UPDATE: As of version 4.3.2 (April 2012) JqGrid now uses jQuery events as described below]

If you’ve ever used JqGrid for anything more than it’s simple, out-of-the-box defaults, chances are you’ve come across problems related to how JqGrid handles events. As it stands (version 4.3.0 at the time of writing), the JqGrid API allows for one and only one event handler per user event. In particular, this approach can be a significant hurdle to constructing plugins to interpret user interactions with the grid. This post demonstrates an alternative approach using jQuery events, allowing for multiple handlers to be bound to the grid.

A full jQuery event plugin for JqGrid using this approach can be found on my github page: https://github.com/CraigCav/jqGrid.events

The JqGrid Event API

To handle events, JqGrid provides an API for specifying a callback to be executed when a named event occurs:

jQuery("#grid").jqGrid({
...
  
onSelectRow: function(id
){
      //do something interesting
 
   },
...
});

This callback can be provided as a option to the grid widget on initialization (as shown) or it can be specified after the grid has been initialized using the setGridParam method. Additionally, it can be set globally by extending the grid defaults:

jQuery.extend(jQuery.jgrid.defaults, {
...
 

   
onSelectRow: function (id, selected
) {
       
//do something interesting 
    },
...
});

Unfortunately this API limits consumers to being able to handle a single callback for each event. Given that as a developer consuming this API, I may wish to be able to provide default settings for handling an event (say, grid load for example) and I may also wish to provide instance specific options for handling the same event, this API is too restrictive to achieve what I require.

Let’s explore an alternative approach to handling user interactions.

jQuery Events

jQuery provides a standard suite of functionality specifically for registering behaviors that take effect when a user interacts with the browser. Of particular interest is the bind method; it allows for an event handler to be attached directly to an element.

$(element).bind(‘click’, function(){
   
//handle click event 
});

A key point to note about the “bind” method is that multiple handlers can be bound to an element. Each handler will be called when the event is triggered for that element.

Applying this mechanism could provide a means to achieve what we need (multiple handlers) that we currently cannot easily achieve using the JqGrid API alone. Unfortunately however, JqGrid does not currently execute any handlers attached in this manner, so our work isn’t over yet.

Triggering Events

We can use jQuery trigger or triggerHandler to work alongside our bind calls to ensure our events get triggered. Perhaps in some later release these methods will be invoked within JqGrid itself (I might submit a patch if I get around to it). Until then, we can wire up the triggers for each interesting event by setting the JqGrid options globally:

jQuery.extend(jQuery.jgrid.defaults, { 
    ...
   
onSelectAll: function (ids, selected
) {
       
$(this).triggerHandler("selectAll.jqGrid", [ids, selected
]);       
    },
   
onSelectRow: function (id, selected
) {
       
$(this).triggerHandler("selectRow.jqGrid", [id, selected
]);
    },
    ...
    
etc    
    ...
});

Each of the available JqGrid event callbacks are now used to trigger the appropriate event handlers. Instead of providing a single extension point for handling events, we can now register as many handlers for each event as we like using bind:

$(element).bind(‘selectRow.jqGrid’, function(event, id, selected){
   
//do something interesting 
});

$(element).bind(‘selectRow.jqGrid’, function(event, id, selected
){
   
//and something awesome
});

The full source of my jQuery event plugin for JqGrid can be found on my github page here: https://github.com/CraigCav/jqGrid.events

Processing ModelState errors returned in Json format using Knockout.js

As part of my quest to become a better JavaScript developer I’ve been experimenting with a really neat little JavaScript library called Knockout. For those unfamiliar with Knockout, here’s a very quick overview:

Knockout is a JavaScript library that helps you to create rich, responsive display and editor user interfaces with a clean underlying data model

The rest of this post will pretty much be a brain dump of some of my recent experiments with the Knockout JavaScript library. We’ll take a little look at some typical procedural style usage of JavaScript, and then show how this can be cleaned up using a more declarative style using Knockout.

Returning Model State as Json

To set the scene, I have a small form in the application I’m working on where some complex server-side validation takes place. When this validation takes place, any broken validation rules are transformed into Json and returned to the client.

The implementation that processed the subsequent json result (based on this post) looked a little like this:

Source Code: View

<div id="operationMessage"><ul></ul></div>

Source Code: Scripts

<script type="text/javascript">

   function ProcessResult(result) {

     $("#operationMessage > ul").empty();

      if (!result.Errors) return true;

      $(‘#operationMessage’).addClass(‘error’);

      for (var err in result.Errors) {

       var errorMessage = result.Errors[err];

       var message = errorMessage;

       $(‘#operationMessage > ul’).append(‘<li> ‘ + message + ‘</li>’);

       }

       return false;          

   }

</script>

The function ProcessResult is called subsequent to receiving the response from a server side call using $.ajax(). The result object contains our list of model state errors in json format.

As you can see, the code takes responsibility for:

  1. Ensuring the UL element of #operationMessage is empty (to ensure only the messages from the current result are displayed)
  2. Adding a css class “error” if there are error messages to display
  3. Pulling out each part of the message, and appending it to the DOM

There are a couple of things worth noting here:

  • The function needs to know about the mark-up of the page, and the mark-up to use to display messages
  • The mark-up in the page needs “hooks” in the form of the id, such that the function can locate where to add messages

In essence, the “what” and the “how” of displaying error messages is all contained in one function; if either of these things are to change we risk impacting both.

Let’s see if we can do better.

View Models

The first step in separating out the concerns of our function, is to define the “what” part – what are trying to display? Let’s make that explicit using a view model. Actually, this is pretty simple for this example; we want to display a list of messages. In traditional JS, this is just an array – but since we’ll be hooking into a little Knockout goodness, we’ll use an observableArray:

var viewModel = {

    errors: ko.observableArray([])

};

The observable part is a knockout feature that lets the UI observe and respond to changes. To populate this model, we’ll simply call viewModel.errors(result.Errors) in place of calling ProcessResult.

JQuery Templates

Now we’ve defined our model, we’ll bind to this model using a jquery template. This will form the View, or the “How” part – defining how we want to display our model. First, lets define an element for our template:

<div data-bind=’template: "validationSummaryTemplate"></div>

And then the template itself:

<script type="text/html" id="validationSummaryTemplate, css: { error: errors().length > 0">

   <ul>

     {{each(i, error) errors}}

     <li>

       ${error}

     </li>            

     {{/each}}

   </ul>

</script>

Pretty concise – we’re simply defining the structure of our page in terms of our view model i.e. for each error in the view model, we’ll render a LI tag containing the error message.

Worth noting is the css-binding – remember that we want to add the error class if there are messages to display – that’s how we do it. We could push this logic onto a property of our view model if we like “hasErrors” but since this isn’t complex, or re-used elsewhere in the view, lets keep it here for now.

To apply the binding, we’ll need one final thing. We need to tell knockout to take effect:

ko.applyBindings(viewModel);

Quick Roundup

What have we gained? The “what” and the “how” are now cleanly separated, and the procedural “processing” JavaScript is completely removed. We also no longer need to dig into a JavaScript method if we wish to change the mark-up for our error items (say, to render a table instead of a list).

When writing JavaScript (much like any other language), it’s all too easy to end up with large swathes of procedural code if we aren’t careful in keeping responsibilities focused and separate.  The primary problem that face us with procedural code comes when we try to scale out complexity.

I’ve found Knockout to be a really good enabler for applying patterns such as MVVM, which in turn helps us to keep complexity at bay.