Friday, 29 May 2009

Using Sys.Observer and jQuery for Template Checkboxes

I was thinking, how do you use those tricky checkboxes with client templates. The problem is that the value bound to the checkbox does not automatically update the data context on the saveChanges() command.

In the client template you can use the sys:commandArgument to return the current dataItem.

<input command="update" commandargument="{{ $dataItem }}" value="Make Live" type="button">

The checkboxes in the template should have the same ID as their datafield

<input id="isReport" value="true" if="isReport==true" checked="checked" type="checkbox">
<input id="isReport" value="true" if="isReport==false" type="checkbox">
<input id="isReport" value="true" if="isReport==null" type="checkbox">

use the clever code:if blocks to display the checkboxes correctly in the first place.

When declaring the template declare a command

fixture = $create(Sys.UI.DataView,
dataProvider: dataContext,
fetchOperation: "categories"
command: saveCommand
null, $get("fixture"));

Then in the saveCommand function loop through all the checkboxes using an if statement to check if it was checked or not and update the dataitem for each with the Sys.Observer.setValue function.

function saveCommand(sender, e) {
//Get the current data item
var data = e.get_commandArgument();
// loop through all the checkboxes and use their id (which is the same as the data field) then add the value back to the dataContext.
$("input:checkbox").each(function() {
var id = $(this).attr("id");
var value = ($(this).attr('checked')) ? true : false;
Sys.Observer.setValue(data, id, value);
dataContext.saveChanges(saved, onfailure);

No comments:

Post a Comment