以下示例用作读取和写入数据的反应式表,包括粘贴和自动填充。
我不知道提供标准 Handsontable API 的 Meteor 智能包。 (Olragon 有一个 smartpackage,但它是用于 Handsontable 的 jQuery API 的)。您可以相当轻松地将文件直接添加到您的项目中:
- 从https://github.com/handsontable/handsontable/releases下载最新版本
- 解压并复制 dist/handsontable.full.js 和 dist/handsontable.full.css 到项目的客户端目录之一(例如 /client/lib/)
-
打开 handsontable.full.js 并更改以下行:
// Remove "var" from Handsontable declaration to add to global scope
var Handsontable = function (rootElement, userSettings) {
...
// New code
Handsontable = function (rootElement, userSettings) {
...
您可能需要卸载任何现有的 Handsontable 智能包
接下来将一个新模板添加到您的 Handsontable 所在的 html 中:
<template name="handsontable">
<div class="handsontable" id="hot"></div>
</template>
最后在你的js文件中:
Meteor.isClient {
Template.handsontable.rendered = function () {
var myData = []; // Need this to create instance
var container = document.getElementById("hot");
var hot = new Handsontable(container,{ // Create Handsontable instance
data: myData,
startRows: 5,
startCols: 5,
colHeaders: true,
minSpareRows: 1,
contextMenu: true,
afterChange: function (change, source) { // "change" is an array of arrays.
if (source !== "loadData") { // Don't need to run this when data is loaded
for (i = 0; i < change.length; i++) { // For each change, get the change info and update the record
var rowNum = change[i][0]; // Which row it appears on Handsontable
var row = myData[rowNum]; // Now we have the whole row of data, including _id
var key = change[i][1]; // Handsontable docs calls this "prop"
var oldVal = change[i][2];
var newVal = change[i][3];
var setModifier = {$set: {}}; // Need to build $set object
setModifier.$set[key] = newVal; // So that we can assign 'key' dynamically using bracket notation of JavaScript object
MyCollection.update(row._id,setModifier);
}
}
}
});
Tracker.autorun( function () { // Tracker function for reactivity
myData = MyCollection.find().fetch(); // Tie in our data
hot.loadData(myData);
});
};
}
关于 afterChange API 的文档在这里:https://github.com/handsontable/handsontable/wiki/Events
此代码将自动将集合的字段呈现为列,包括 _id 列。要在 Meteor 中使用 Handsontable 定义列,下面是示例集合 Books 中的示例文档:
{_id: 'Hneb7LxFRptXCiL49',
title: 'The Name of the Wind',
author: 'Patrick Rothfuss',
copies: 3 }
我们可以指定我们的列,这样 _id 就不会出现,以及(可选地)为我们的 colHeaders 命名:
// replace at "colHeaders":
colHeaders: ['Title','Author','Copies'],
columns: [
{data: 'title'},
{data: 'author:},
{data: 'copies'}
],
// ...