Meteor Handsontable Example
The following example works like a reactive table that reads and writes data including insert and autocomplete.
I am not aware of the smart package Meteor that provides the standard Handsontable API. (There is one smartpackage from Olragon, but it's for the jQuery API for Handsontable). You can easily add files to your project:
- Download the latest version https://github.com/handsontable/handsontable/releases
- Unzip and copy dist / handsontable.full.js and dist / handsontable.full.css to one of your client project directories (e.g. / client / lib /)
-
Open handsontable.full.js and change the following line:
// Remove "var" from Handsontable declaration to add to global scope var Handsontable = function (rootElement, userSettings) { ... // New code Handsontable = function (rootElement, userSettings) { ...
-
You may need to remove any existing Handsontable Smart Packages
Then add a new template to your html where your Handsontable will reside:
<template name="handsontable">
<div class="handsontable" id="hot"></div>
</template>
Finally, in the js file:
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);
});
};
}
The on afterChange API docs are here: https://github.com/handsontable/handsontable/wiki/Events
This code will automatically convert your collection fields to columns including the _id column. To define columns using Handsontable in Meteor, here is a sample document in the Books sample collection:
{_id: 'Hneb7LxFRptXCiL49',
title: 'The Name of the Wind',
author: 'Patrick Rothfuss',
copies: 3 }
We can specify our columns so that _id is not displayed and also (optionally) give names to our commands:
// replace at "colHeaders":
colHeaders: ['Title','Author','Copies'],
columns: [
{data: 'title'},
{data: 'author:},
{data: 'copies'}
],
// ...
source to share