Skip to content

Instantly share code, notes, and snippets.

@SteveSanderson
Created April 7, 2011 17:44
Show Gist options
  • Save SteveSanderson/908284 to your computer and use it in GitHub Desktop.
Save SteveSanderson/908284 to your computer and use it in GitHub Desktop.
Simple general-purpose "grid" binding
// Simple general-purpose "grid" binding
// Note: this is just a spike
ko.bindingHandlers.grid = {
init: function(element, valueAccessor) {
var value = valueAccessor();
var grid = $(element).grid({
columns: value.columns,
source: ko.utils.unwrapObservable(value.data).slice(0),
selectMode: value.selectMode,
select: function(event, ui) {
if (value.selectedItem)
value.selectedItem(ui.selectedItem.data);
}
}).data( "grid" );
$.setField(grid, "source", ko.utils.unwrapObservable(value.data).slice(0));
},
update: function(element, valueAccessor) {
var value = valueAccessor();
var grid = $(element).data("grid");
var editScript = ko.utils.compareArrays(grid.source, value.data());
for(var i = 0; i < editScript.length; i++) {
switch(editScript[i].status) {
case "added":
$.changeArray(grid.source, "push", editScript[i].value);
break;
case "deleted":
var index = $.inArray(editScript[i].value, grid.source);
if (index >= 0)
$.changeArray(grid.source, "splice", index, 1);
break;
}
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment