-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
knockout.html
92 lines (79 loc) · 2.78 KB
/
knockout.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Knockout.js demo</title>
<link rel="stylesheet" href="demo.css"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.5.0/knockout-debug.js"></script>
<script src="../dist/gridstack-all.js"></script>
</head>
<body>
<div class="container-fluid">
<h1>knockout.js Demo</h1>
<div>
<a class="btn btn-primary" data-bind="click: addNewWidget">Add Widget</a>
</div>
<br>
<div data-bind="component: {name: 'dashboard-grid', params: $data}"></div>
</div>
<script type="text/javascript">
ko.components.register('dashboard-grid', {
viewModel: {
createViewModel: function (controller, componentInfo) {
let ViewModel = function (controller, componentInfo) {
let grid = null;
this.widgets = controller.widgets;
this.afterAddWidget = function (items) {
if (!grid ) {
grid = GridStack.init({auto: false});
}
let item = items.find(function (i) { return i.nodeType == 1 });
grid.makeWidget(item);
ko.utils.domNodeDisposal.addDisposeCallback(item, function () {
grid.removeWidget(item);
});
};
};
return new ViewModel(controller, componentInfo);
}
},
template:
[
'<div class="grid-stack" data-bind="foreach: {data: widgets, afterRender: afterAddWidget}">',
' <div class="grid-stack-item" data-bind="attr: {\'gs-x\': $data.x, \'gs-y\': $data.y, \'gs-w\': $data.w, \'gs-h\': $data.h, \'gs-auto-position\': $data.auto_position, \'gs-id\': $data.id}">',
' <div class="grid-stack-item-content"><button data-bind="click: $root.deleteWidget">Delete me</button></div>',
' </div>',
'</div> '
].join('')
});
let Controller = function (widgets) {
let self = this;
this.widgets = ko.observableArray(widgets);
this.addNewWidget = function () {
this.widgets.push({
x: 0,
y: 0,
w: Math.floor(1 + 3 * Math.random()),
h: Math.floor(1 + 3 * Math.random()),
auto_position: true
});
return false;
};
this.deleteWidget = function (item) {
self.widgets.remove(item);
return false;
};
};
let widgets = [
{x: 0, y: 0, w: 2, h: 2, id: '0'},
{x: 2, y: 0, w: 4, h: 2, id: '1'},
{x: 6, y: 0, w: 2, h: 4, id: '2'},
{x: 1, y: 2, w: 4, h: 2, id: '3'}
];
let controller = new Controller(widgets);
ko.applyBindings(controller);
</script>
</body>
</html>