Guest User

Untitled

a guest
Jul 16th, 2018
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.32 KB | None | 0 0
  1. CTreeDataItem = Backbone.Model.extend(
  2. {
  3. });
  4. CTreeDataItems = Backbone.Collection.extend(
  5. {
  6. model: CTreeDataItem
  7. });
  8.  
  9. var treeJs =
  10. [
  11. { id: "tvRoot", title: 'Root', cssClass: 'root',
  12. items: [
  13. { id: "ti1", title: 'Item1', cssClass: 'item',
  14. items: [
  15. { id: "ti11", title: 'SubItem11', cssClass: 'subitem'},
  16. { id: "ti12", title: 'SubItem12', cssClass: 'subitem'}]},
  17. { id: "ti2", title: 'Item2', cssClass: 'item',},
  18. { id: "ti3", title: 'Item3', cssClass: 'item',
  19. items: [
  20. { id: "ti31", title: 'SubItem31', cssClass: 'subitem'},
  21. { id: "ti32", title: 'SubItem32', cssClass: 'subitem'},
  22. { id: "ti33", title: 'SubItem33', cssClass: 'subitem'}]}]
  23. }];
  24. this.TreeData = new CTreeDataItems();
  25. this.TreeData.add(treeJs);
  26.  
  27. var CTreeDataItem = Backbone.Model.extend({
  28. initialize: function() {
  29. if (Array.isArray(this.get('items'))) {
  30. this.set({items: new CTreeDataItemChildren(this.get('items'))});
  31. }
  32. }
  33. });
  34.  
  35. // children collection
  36. var CTreeDataItemChildren = Backbone.Collection.extend({
  37. model: CTreeDataItem
  38. });
  39.  
  40. // create
  41. var treeData = new CTreeDataItemChildren(treeJs);
  42.  
  43. // access
  44. treeData.at(0).get('items').at(1).get('title')
  45. // returns "Item2"
  46.  
  47. // flatten the tree outside of Backbone. Alternatively,
  48. // you could override the constructor of the CTree collection
  49. // to provide encapsulation
  50. function flatten(parentID, arr) {
  51. var out = [];
  52. for (var i = 0; i < arr.length; i++) {
  53. var node = arr[i];
  54. node.parentID = parentID;
  55. out.push(node);
  56. if (Array.isArray(node.items))
  57. Array.prototype.push.apply(out, flatten(node.id, node.items));
  58. delete node.items;
  59. }
  60. return out;
  61. }
  62.  
  63. // remove above code that would have provided nesting
  64. var CTreeDataItem = Backbone.Model.extend({});
  65.  
  66. // children collection, as before
  67. var CTreeDataItemCollection = Backbone.Collection.extend({
  68. model: CTreeDataItem
  69. });
  70.  
  71. // create
  72. var treeData = new CTreeDataItemChildren(flatten('', treeJs));
  73.  
  74. // as before, but now there's the 'parentID' FK
  75. treeData.at(3).get('parentID')
  76. // returns "ti1"
Add Comment
Please, Sign In to add comment