0

I have a couple of paths, it could be unlimited i depth and amount of paths.

Im using backbone, and getting data from a server, each model containing a path field for example:

"/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"

I want to group the models so that I can represent the file structure in my web app, so that you can click on "home" and it lists all its relative directories and so on. So you can click further into the structure until there is no more files or directories in that folder/directory.

Harry
  • 13,091
  • 29
  • 107
  • 167
  • Here is a relevant question on hierarchical data in Backbone.js: http://stackoverflow.com/questions/7682805/backbone-js-and-hierarchies-trees – George Jan 21 '13 at 14:51
  • Thanks George. The example used a parent_id attribute which links to the paths to each other, in my case i just have a path. Not sure how it would be implemented in the example. – Harry Jan 21 '13 at 15:05

1 Answers1

0

One solution would just be to parse those paths in to a set of Collections. Something like:

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);
    }
}

Then, inside PathCollection you could override the add method to do something similar (ie. look at the first part of the models' relative paths and add them to the appropriate Collection), like so:

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);
        } 
    }
})

Of course, you'll likely want to make that more generic, and split on "/" characters rather than doing specific indexOf checks on specific paths, but hopefully you get the idea. The point is that if you write a collection that checks its member models' paths, and adds them to other collections as appropriate, then at the end of the day you'll wind up with a nice nested series of Collections.

Once you have that, checking which models fall under which paths becomes trivial; to get the models under the /home/harry/ path for instance you would just do:

home.harry.models;
machineghost
  • 33,529
  • 30
  • 159
  • 234