2013-01-21 22 views
0

我有幾條路徑,它可以是無限深度和路徑數量。利用骨幹相對路徑列表 - 根據路徑對它們進行分組

1m,並從服務器獲取數據,包含路徑字段,例如每個模型:

"/home/harry/" 
"/home/sally/" 
"/home/sally/personal" 
"/home/harry/files" 
"/home/harry/photos" 
"/home/harry/videos" 
"/home/harry/files/documents" 
"/home/harry/files/personal" 
"/home/harry/photos/2012" 
"/home/harry/photos/2011" 
"/home/harry//videos/2012" 
"/home/harry/videos/edited" 
"/home/harry/videos/edited/other/trash_this" 

我想組的機型,這樣我可以在我的web應用程序代表了文件結構,這樣你就可以點擊「home」並列出所有的相關目錄等等。因此,您可以進一步點擊該結構,直到該文件夾​​/目錄中沒有更多文件或目錄。

+0

這裏是在Backbone.js的分層數據相關的問題:http://stackoverflow.com/questions/7682805/ backbone-js-and-hierarchies-trees –

+0

謝謝喬治。該示例使用了一個parent_id屬性,它鏈接到彼此的路徑,在我的情況下,我只是有一個路徑。不確定在示例中它將如何實現。 – Harry

回答

0

一種解決方案只是將這些路徑解析爲一組集合。喜歡的東西:

var home = new PathCollection({}); 
_(models).each(function(model) { 
    if (model.get('path').indexOf('/home/') == 0) { 
     model.set('relativePath', model.get('path').substr(6)) ; ditch '/home/' 
     home.add(model); 
    } 
} 

然後,裏面PathCollection你可以重寫add方法做同樣的事情,像這樣(即看模型的相對路徑的第一部分,並將其添加到相應的集合。):

var PathCollection = Backbone.Collection.extend({ 
    add: function(model) { 
     // NOTE: This is naive; a real add would need to accept multiple models 
     if (model.get('relativePath').indexOf('harry/') == 0) { 
      // create harry collection if it doesn't exist 
      if (!this.harry) this.harry = new PathCollection(); 
      this.harry.add(model); 
     } 
    } 
}) 

當然,你可能會想使更多的通用性,並在「/」字符,而不是做具體的路徑具體indexOf檢查分裂,但希望你的想法。重點是,如果您編寫一個檢查其成員模型路徑的集合,並將它們添加到其他集合中,那麼在一天結束時,您將得到一個很好的嵌套系列集合。

一旦你有了,檢查哪些模型屬於哪些路徑變得微不足道;拿到車型的/ home /哈利/路徑下,比如你只想做:

home.harry.models;