Using knockout js am trying to create a table which will have 4rows and 4coulmns. Below is my array which will have 16 elements which will be needed to be put inside the table.
/*----------------------------------------------------------------------*/
/* View Model */
/*----------------------------------------------------------------------*/
function ViewModel() {
var self = this;
self.items = ko.observableArray(["1.jpg",
"2.jpg",
"3.jpg",
"4.jpg",
"5.jpg",
"6.jpg"
]);
self.itemRows = ko.computed(function () { //computes the rows dynamically based on items
var rows = [];
var count = 0;
var items = self.items(); //get the item array
var current = [];
for(var i in items)
{
var item = items[i];
current.push(item);
count++;
if (count == 4)
{
count = 0;
rows.push(current);
current = []; //next array
}
}
if (current.length > 0)
{
rows.push(current);
}
return rows;
});
self.bindSort = function() {
var startIndex = -1;
var sortableSetup = {
start: function (event, ui)
{
startIndex = ui.item.index();
},
stop: function (event, ui)
{
var newIndex = ui.item.index();
if (startIndex > -1)
{
self.from = ko.observable(startIndex);
self.to = ko.observable(newIndex);
var iTo = parseInt(self.to());
var iFrom = parseInt(self.from());
var from = self.items()[iFrom];
var to = self.items()[iTo];
self.items()[iTo] = from;
self.items()[iFrom] = to;
//alert('before');
// alert(from);
// alert(to);
var fromA = self.items()[iFrom];
var toA = self.items()[iTo];
//alert('after');
//alert(fromA);
// alert(toA);
self.items.remove(from);
self.items.splice(newIndex, 0, toA);
self.items.remove(to);
self.items.splice(startIndex, 0, fromA);
//ui.item.remove();
self.items.valueHasMutated();
}
}
};
$(".fruitList").sortable( sortableSetup );
};
}
/*----------------------------------------------------------------------*/
/* KO HTML Binding */
/*----------------------------------------------------------------------*/
$(document).ready(function() {
// create the view model
var model = new ViewModel();
// call the bind method for jquery UI setup
model.bindSort();
// binds ko attributes with the html
ko.applyBindings(model);
});
and trying to do this in html,
<table data-bind="foreach: itemRows">
<tr class="fruitList" data-bind="foreach: $data">
<td><img data-bind="attr: { src: $data }" /></td>
</tr>
</table>
I am not able to get the length of the array and also how can i break the loop once it creates 4 tds in the first and then create the second row.. Any suggestion ???
Update:
Below code doesnt seem to work when i use sortable,
start: function (event, ui)
{
startIndex = ui.item.index();
},
stop: function (event, ui)
{
var newIndex = ui.item.index();