来自gridstack.js的示例并在此处实现:
http://jsfiddle.net/m3qj3qs1/1/
HTML:
<div class="container-fluid">
<h1>knockout.js Demo</h1>
<div>
<button data-bind="click: add_new_widget">Add new widget</button>
</div>
<br>
<div data-bind="component: {name: 'dashboard-grid', params: $data}"></div>
</div>
<template id="gridstack-template">
<div class="grid-stack" data-bind="foreach: {data: widgets, afterRender: afterAddWidget}">
<div class="grid-stack-item" data-bind="attr: {'data-gs-x': $data.x, 'data-gs-y': $data.y, 'data-gs-width': $data.width, 'data-gs-height': $data.height, 'data-gs-auto-position': $data.auto_position}">
<div class="grid-stack-item-content"><button data-bind="click: $root.delete_widget">Delete me</button></div>
</div></div><!-- <---- NO SPACE BETWEEN THESE CLOSING TAGS -->
</template>
JS:
ko.components.register('dashboard-grid', {
viewModel: {
createViewModel: function (controller, componentInfo) {
var ViewModel = function (controller, componentInfo) {
var grid = null;
this.widgets = controller.widgets;
this.afterAddWidget = function (items) {
if (grid == null) {
grid = $(componentInfo.element).find('.grid-stack').gridstack({
auto: false
}).data('gridstack');
}
var item = _.find(items, function (i) { return i.nodeType == 1 });
grid.add_widget(item);
ko.utils.domNodeDisposal.addDisposeCallback(item, function () {
grid.remove_widget(item);
});
};
};
return new ViewModel(controller, componentInfo);
}
},
template: { element: 'gridstack-template' }
});
$(function () {
var Controller = function (widgets) {
var self = this;
this.widgets = ko.observableArray(widgets);
this.add_new_widget = function () {
this.widgets.push({
x: 0,
y: 0,
width: Math.floor(1 + 3 * Math.random()),
height: Math.floor(1 + 3 * Math.random()),
auto_position: true
});
};
this.delete_widget = function (item) {
self.widgets.remove(item);
};
};
var widgets = [
{x: 0, y: 0, width: 2, height: 2},
{x: 2, y: 0, width: 4, height: 2},
{x: 6, y: 0, width: 2, height: 4},
{x: 1, y: 2, width: 4, height: 2}
];
var controller = new Controller(widgets);
ko.applyBindings(controller);
});
在示例中加载了4个小部件(数组),定义了一个模板和一个挖空组件。
如何为不同的小部件指定不同的模板?每个小部件一个模板的示例?
答案 0 :(得分:0)
您也可以将组件用于小部件。以下是它的外观示例:
<div class="grid-stack-item-content"><div data-bind="component: {name: type, params: $data}"></div></div>
当然,您的小部件必须包含type
:
var widgets = [
{x: 0, y: 0, width: 2, height: 2, type: 'widgetA'},
{x: 2, y: 0, width: 4, height: 2, type: 'widgetB'},
{x: 6, y: 0, width: 2, height: 4, type: 'widgetC'},
{x: 1, y: 2, width: 4, height: 2, type: 'widgetD'}
];
您需要定义这些小部件。请查看淘汰文档http://knockoutjs.com/documentation/component-overview.html