Skip to content

Instantly share code, notes, and snippets.

@latentflip
Last active August 29, 2015 14:06
Show Gist options
  • Save latentflip/080a14052edf067654e7 to your computer and use it in GitHub Desktop.
Save latentflip/080a14052edf067654e7 to your computer and use it in GitHub Desktop.
Rendering a tree with ampersand
var AmpersandState = require('ampersand-state');
var AmpersandCollection = require('ampersand-collection');
var View = require('ampersand-view');
var NodeList = AmpersandCollection.extend({
});
var Node = AmpersandState.extend({
props: {
id: 'string',
name: 'string'
},
collections: {
children: NodeList
}
});
NodeList.prototype.model = Node;
var data = {
id: '1',
name: 'root',
children: [
{ id: '2', name: '1-2', children: [
{ id: '5', name: '1-2-5' }, { id: '6', name: '1-2-6' }, { id: '7', name: '1-2-7' },
]},
{ id: '3', name: '1-3' },
{ id: '4', name: '1-4' },
]
};
var rootNode = new Node(data);
var NodeView = View.extend({
template: '<li><span data-hook="id"></span>: <span data-hook="name"></span><ul data-hook="children"></ul></li>',
bindings: {
'model.id': "[data-hook=id]",
'model.name': "[data-hook=name]"
},
render: function () {
this.renderWithTemplate();
if (this.model && this.model.children) {
this.renderCollection(this.model.children, NodeView, this.queryByHook('children'));
}
}
});
var view = new NodeView({ model: rootNode });
var ul = document.createElement('ul');
document.body.appendChild(ul);
view.render();
ul.appendChild(view.el);
@stoikerty
Copy link

Hi ya, I was wondering why you used NodeList.prototype.model = Node; instead of passing the Node model to NodeList as you did in the first version?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment