Skip to content

Instantly share code, notes, and snippets.

@HenrikJoreteg
Created September 5, 2014 02:59
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 HenrikJoreteg/e76d72b0559ae9b6061b to your computer and use it in GitHub Desktop.
Save HenrikJoreteg/e76d72b0559ae9b6061b to your computer and use it in GitHub Desktop.
Nested models in Ampersand.js
// credit for this goes to @latentflip
var State = require('ampersand-state');
var Collection = require('ampersand-collection');
var OptionList = Collection.extend({
//Circular reference so we have to function wrap this
model: function (data, options) {
return new Option(data, options);
}
});
var Option = State.extend({
initialize: function () {
this.hasChildren = !!this.options.length;
},
props: {
key: 'string',
title: 'string',
description: 'string',
isRoot: ['boolean', true, false],
hasChildren: 'boolean',
popular: ['boolean', true, false]
},
collections: {
options: OptionList
},
findByProperty: function (property, value) {
var result = [];
var self = this;
function findOptions(model) {
if (model[property] === value) {
result.push(model);
}
model.options.each(findOptions);
}
findOptions(this);
return result;
}
});
OptionList.model = Option;
module.exports = Option;
module.exports.OptionList = OptionList;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment