Knockout - MVVM basics - function
HTML
<link rel="stylesheet" href="http://testgridster.azurewebsites.net/gridster.css">
<script src="http://testgridster.azurewebsites.net/gridster.js"></script>
<script src="http://testgridster.azurewebsites.net/knockout.js"></script>
<!-- The with: $data is necessary to render the children before calling the gridster binding handler -->
<div class="gridster" data-bind="template: { afterRender: initializeGridster }">
<ul data-bind="template: { foreach: myData, beforeRemove: removeGridster, afterAdd: addGridster }">
<li data-bind="attr: { 'id': id, 'data-row': datarow, 'data-col': datacol, 'data-sizex': datasizex, 'data-sizey': datasizey } ">
<span data-bind="text: text"></span>
<button data-bind="click: $root.deleteOne">Delete</button>
</li>
</ul>
<button data-bind="click: addOne">Add</button>
<button data-bind="click: removeAll">Empty</button>
</div>
CSS
/*! gridster.js - v0.1.0 - 2012-10-20
* http://gridster.net/
* Copyright (c) 2012 ducksboard; Licensed MIT */
body {
background-color: #011529;
}
li {
background-color: #FFFFFF;
list-style: none;
}
JavaScript
//This is some widget data to start the process
var gridData = [
{id: "1", text:'Widget #1', datarow:1, datacol:1, datasizex:1, datasizey:1},
{id: "2", text:'Widget #2', datarow:1, datacol:2, datasizex:2, datasizey:1},
{id: "3", text:'Widget #3', datarow:1, datacol:4, datasizex:1, datasizey:1},
{id: "4", text:'Widget #4', datarow:2, datacol:1, datasizex:1, datasizey:2}
];
// The viewmodel contains an observable array of widget data to be
// displayed on the gridster
var viewmodel = function () {
var self = this;
self.myData = ko.observableArray(gridData);
self.nextId = 5;
self.gridster = undefined;
// AddOne adds an element to the observable array.
// Notice how I'm not adding the element to gridster by hand here. This means that whatever
// the source of the add (click, callback, web sockets event), the element will be added to gridster.
self.addOne = function () {
myViewModel.myData.push({
text: 'Widget Added After!',
datarow: 1,
datacol: 1,
datasizex: 1,
datasizey: 1,
id: self.nextId++
});
};
self.removeAll = function() {
var length = self.myData().length;
for (var cpt = 0; cpt < length; cpt++) {
self.myData.pop();
}
};
self.deleteOne = function (item) {
self.myData.remove(item);
};
self.initializeGridster = function(elements) {
self.gridster = $(".gridster > ul").gridster({
widget_margins: [5, 5],
widget_base_dimensions: [120, 120],
draggable: {
stop: function (event, ui) {
$.each(self.myData(), function (index, obj) {
var widget = $("#" + obj.id);
obj.datacol = parseInt(widget.attr("data-col"));
obj.datarow = parseInt(widget.attr("data-row"));
...