Skip to content

Instantly share code, notes, and snippets.

@timwis
Last active December 22, 2015 12:46
Show Gist options
  • Save timwis/a76d9c2d438bd06021cd to your computer and use it in GitHub Desktop.
Save timwis/a76d9c2d438bd06021cd to your computer and use it in GitHub Desktop.
Use an Ampersand Collection with Handsontable
var Handsontable = require('handsontable')
var AmpersandModel = require('ampersand-model')
var AmpersandRestCollection = require('ampersand-rest-collection')
var _ = require('lodash')
var Person = AmpersandModel.extend({
props: {
id: 'number',
name: 'string',
address: 'string'
}
})
// Shim push, slice, and splice -- handsontable expects these methods
// but ampersand doesn't have them out of the box
var People = AmpersandRestCollection.extend({
model: Person,
push: function (model, options) {
return this.add(model, _.extend({at: this.length}, options))
},
slice: function () {
return Array.prototype.slice.apply(this.models, arguments)
},
splice: function () {
return Array.prototype.splice.apply(this.models, arguments)
}
})
var data = [
{id: 1, name: 'Ted Right', address: ''},
{id: 2, name: 'Frank Honest', address: ''},
{id: 3, name: 'Joan Well', address: ''},
{id: 4, name: 'Gail Polite', address: ''},
{id: 5, name: 'Michael Fair', address: ''}
]
var people = new People(data)
// Helper function to get/set ampersand model properties. Unfortunately
// necessary because ampersand models don't expose their members like and object
function col (attr) {
return {
data: function (row, val) {
if (val !== undefined) {
row[attr] = val
}
return row[attr]
}
}
}
var container = document.querySelector('#grid')
var grid = new Handsontable(container, {
data: people,
columns: [
col('id'),
col('name'),
col('address')
],
colHeaders: true,
rowHeaders: true,
minSpareCols: 1,
minSpareRows: 1
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment