I currently have a Model that is related back to itself in a parent-child relationship. I need to be able to display these in a tree-like structure on the page (i.e. Nested <li>
items). Each <li>
item will have an underlying HTML structure that has various data-binding and event handlers (all implemented with Rivets.js).
My initial thought is to create a component with Rivets.js, and then just nest it within itself. However, I can't seem to wrap my head around how these would be initialized and inserted into the DOM.
Here is what I would like to be able to do:
/** DATA LAYER **/
var item = {
id: 1,
title: "test item 1",
description: "my description 1",
someHandler: function () {
console.log("handle something for Item 1");
},
items: [
{
id: 2,
parentItem: 1,
title: "test item 2",
description: "my description 2",
someHandler: function () {
console.log("handle something for Item 2");
},
items: [
]
},
{
id: 3,
parentItem: 1,
title: "test item 3",
description: "my description 3",
someHandler: function () {
console.log("handle something for Item 3");
},
items: [
{
id: 4,
parentItem: 3,
title: "test item 4",
description: "my description 4",
someHandler: function () {
console.log("handle something for Item 4");
},
items: [
]
}
]
}
]
};
And the presentation layer:
/** TEMPLATE **/
<div id="item_template"> <!-- accessed via <my-new-item></my-new-item> in HTML -->
<li>
<h4 rv-text="title"></h4>
<p rv-html="description"></p>
<button rv-click="someHandler">Click Me!</button>
<ol>
<my-new-item rv-each-item="items" item="item"></my-new-item>
</ol>
</li>
</div>
And the business layer:
rivets.components['my-new-item'] = {
template: function() {
return document.querySelector('#item_template').innerHTML;
},
initialize: function(el, data) {
return data;
}
}
rivets.init('my-new-item', document.querySelector('#page'), item);
Is there a way to recursively nest components in RivetsJS?
UPDATE
I've put together a jsfiddle to illustrate this. I can't seem to get the data-binding to work during the recursion.
OK, the solution is here:
https://jsfiddle.net/0mv4r8w0/5/
Apparently, I need to explicitly define a property to access the data.
The template changes to (note that I'm using
item.*
to access properties now):and the
rivits.init
call changes to (note the data is set to a property now):