Created
January 24, 2012 22:12
-
-
Save dhollenbeck/1673049 to your computer and use it in GitHub Desktop.
backbone.js collection with nested models for a nested list menu
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
App.collections.Menuitems = App.collections.Collection.extend({ | |
model : App.models.Menuitem, | |
url : './api/menuitems', | |
initialize: function(options){ | |
this.bind('reset', this.relationships); //collection loads so calculate relationships | |
}, | |
relationships: function(){ | |
this.relations = _.groupBy(this.models, this.parent); | |
}, | |
//return an array of root models | |
root: function(){ | |
if(!this.relations) this.relationships(); | |
return this.relations[0]; | |
}, | |
//return an array of child models | |
children: function(model){ | |
if(!this.relations) this.relationships(); | |
return (typeof this.relations[model.id] === 'undefined')? [] : this.relations[model.id]; | |
}, | |
//return parent_id or 0 if model.parent_id is undefined | |
parent: function(model){ | |
var parent_id = model.get('parent_id'); | |
return (!parent_id)? 0: parent_id; | |
} | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script type="text/template" id="menu-item-template"><a id="menu-item-<%=id %>" href="<%=href %>" title="<%= title %>"><%=text %></a></script> | |
<script type="text/template" id="menu-template"><h1>Menu</h1></script> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{"result":[ | |
{"id":1,"href":"#\/","text":"Home","title":"Home"}, | |
{"id":2,"href":"#\/persons","text":"Persons","title":"Person listing"}, | |
{"id":4,"href":"#\/xxxx","text":"Broken link","title":""}, | |
{"id":5,"href":"http:\/\/www.google.com","text":"www.google.com","title":"","parent_id":4}, | |
{"id":6,"href":"http:\/\/www.ibm.com","text":"www.ibm.com","title":"","parent_id":5} | |
]} |
hi dhollenbeck,
your code helped me to create this http://bit.ly/1cyFaPY and http://bit.ly/1chPnkS.
thank you!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi dhollenbeck,
i used your code and its great. but one problem its binding 1 event 2 time on sub list.
here you can check http://plnkr.co/1rsGe5NXz5PQx0kc7vYh