Meteor Handsontable示例

Lob*_*san 3 meteor handsontable

有没有人有一个使用meteor和handsontable的工作示例来创建一个反应表来读取和更新数据?

在此先感谢您的帮助

Muf*_*asa 6

以下示例用作读取和写入数据的响应表,包括粘贴和自动填充.

我不知道Meteor smartpackage提供标准的Handsontable API.(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) {
     ...
    
    Run Code Online (Sandbox Code Playgroud)
  • 您可能需要卸载任何现有的Handsontable智能包

接下来,在您的Handsontable所在的html中添加一个新模板:

<template name="handsontable">
<div class="handsontable" id="hot"></div>
</template>
Run Code Online (Sandbox Code Playgroud)

最后在你的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);
  });
 };
}
Run Code Online (Sandbox Code Playgroud)

关于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 }
Run Code Online (Sandbox Code Playgroud)

我们可以指定我们的列,以便_id不会显示,以及(可选)为colHeaders指定名称:

// replace at "colHeaders":
colHeaders: ['Title','Author','Copies'],
columns: [
  {data: 'title'},
  {data: 'author:},
  {data: 'copies'}
],
// ...
Run Code Online (Sandbox Code Playgroud)