Skip to content

Instantly share code, notes, and snippets.

@coreybutler
Created July 10, 2016 00:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save coreybutler/6afbaaae2fc559297df187f3e20e45ed to your computer and use it in GitHub Desktop.
Save coreybutler/6afbaaae2fc559297df187f3e20e45ed to your computer and use it in GitHub Desktop.
Nested NGN.DATA.Store example
<html>
<body>
Test
<script src="./init/core.js"></script>
<script src="./shared/core.js"></script>
<script src="./ngn.js"></script>
<script src="./eventemitter.js"></script>
<script src="./bus.js"></script>
<script src="./shared/exception.js"></script>
<script src="./init/exception.js"></script>
<script src="./net.js"></script>
<script src="./shared/data/utility.js"></script>
<script src="./shared/data/model.js"></script>
<script src="./shared/data/store.js"></script>
<script>
let Animal = new NGN.DATA.Model({
fields: {
name: null,
type: {
type: String,
enum: ['dog', 'cat', 'iguana', 'guinea pig']
}
}
})
// let Pets = new NGN.DATA.Store({
// model: Animal
// })
let Person = new NGN.DATA.Model({
fields: {
firstname: null,
lastname: null,
dob: Date,
gender: {
type: String,
default: 'm',
required: true
}
},
relationships: {
pets: [Animal]
}
})
let People = new NGN.DATA.Store({
model: Person
})
People.on('record.update', function (record, change) {
if (change.field === 'pets') {
const diff = Math.abs(change.new.length - change.old.length)
if (change.old.length < change.new.length) {
console.warn(record.firstname + ' got ' + diff + ' new pet' + (diff === 1 ? '' : 's') + '.')
} else if (change.old.length > change.new.length) {
console.warn(record.firstname + ' got rid of ' + diff + ' new pet' + (diff === 1 ? '' : 's') + '.')
}
console.warn(record.firstname + ' has the following pets:')
console.table(record.pets.data)
}
})
let Corey = new Person({
firstname: 'Corey',
lastname: 'Butler',
dob: new Date(),
pets: []
})
People.add(Corey)
People.add({
firstname: 'Graham',
lastname: 'Butler',
pets: [{
name: 'Spaceman Spiff',
type: 'iquana'
}, {
name: 'Deadbeat',
type: 'bat'
}]
})
console.info('Folks')
console.table(People.data)
Corey.pets.add({
name: 'Jake',
type: 'dog'
})
setTimeout(function () {
Corey.pets.add({
name: 'Pippet',
type: 'dog'
})
setTimeout(function () {
Corey.pets.add({
name: 'Scamper',
type: 'guinea pig'
})
}, 2000)
}, 1500)
People.last.pets.remove(People.last.pets.first)
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment