Backbone.js的和等级/棵 [英] Backbone.js and hierarchies/trees

查看:79
本文介绍了Backbone.js的和等级/棵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的工作已经需要一个表单,允许用户可以管理到任意深度的产品类别层次的应用。我可以pretty轻松获取数据到页面上,但我有点丢失什么,我需要做的,做出这样的事工作,Backbone.js的。基本上,我在找嵌套的UL。当用户选择一个,我希望他们能够编辑/删除类别或添加其他类别它的下面。

I'm working on an application that has need of a form that allows the user to manage a hierarchy of product categories that go to an arbitrary depth. I can pretty easily get the data onto the page, but I'm a bit lost as to what I need to do to make such a thing work with backbone.js. Basically, I'm looking for nested ULs. When the user selects one, I want them to be able to edit/delete the category or add another category underneath it.

我在线上无法找到的情况下如果有人在Backbone.js的相同数据类型的任意深度的层次。我只想让我的模型类包含我的收藏类的实例?如何将储蓄来实现?我知道这是一个有点宽泛的问题,但我主要需要对如何处理这个的一般建议(或更好,但地方取样中我没有看过)。

I'm having trouble finding cases online where someone has an arbitrarily deep hierarchy of the same data type in backbone.js. Would I just make my model class contain an instance of my collection class? How would saving be accomplished? I know this is a bit of a broad question, but I'm mainly in need of some general suggestions for how to approach this (or better yet, a sample somewhere that I haven't looked).

推荐答案

您可以将树模型与亲子链接项目的集合。所以,你的模型应该是这样的:

You can model a tree as a collection of items with parent-child links. So your model should have something like this:

      id:           id,
      parent_id:    parent_id 

然后使用在JS递归函数调用集合构建树。这里是一块活code:

Then build a tree from a collection using recursive function calls in JS. Here is a piece of live code:

 function buildTree(branch, list) {
  //recursively builds tree from list with parent-child dependencies
  if (typeof branch == 'undefined') return null;
  var tree = [];
  for(var i=0; i<branch.length; i++)      
    tree.push( {
      item: branch[i],
      children: buildTree( list[ branch[i].id ], list)
    });
  return tree;
}

呼叫使用PARENT_ID underscore.js功能组项目(这是一个Backbone.js的prerequisite反正),然后调用之前:

Before calling the function group items by parent_id using underscore.js (which is a prerequisite for backbone.js anyway), and then call:

  var list = _.groupBy(arrayOfItems,'parent_id');
  var tree = buildTree(list[0],list); 

最后,(在这里没有例子,但我相信你有这个想法)渲染使用递归函数树再次呼吁。

Finally, render the tree using recursive function calls again (no example here, but I believe you got the idea).

PS。如果你指明正确的PARENT_ID添加/存储项目shoudn't是一个问题。

PS. Adding/saving an item shoudn't be a problem if you indicate right parent_id.

这篇关于Backbone.js的和等级/棵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆