简体   繁体   中英

Using a Model to Filter/Sort a Collection in Backbone.js

After several days of reading tutorials and searching The Google I have hit a wall...

I'm creating an app using backbone.js that has an Item Model / Items Collection with various views to show the Items. A portion of the app will allow users to create groups (and use existing groups) to display a subset of the Items Collection.

There will be a Group Model / Groups Collection with various views to show the groups and allow users to associate Items with a specific group.

The problem is that each item can belong to one, many or none of the groups and I cannot figure out how to use the Group Model to get a subset of the Items Collection based on what items have been associated with it or this is even the right way to go about it.

Any help would really be appreciated!

Depending on how many models you actually have, where you will be storing them, and how they will be rendered in the UI will depend on how you go about approaching this.

If there are many models, which are stored in a database on a remote server, and items of groups will be rendered separately, one way would to go would be to load the items of the group on demand. Maybe something like ...

var Item = Backbone.Model.extend({});
var ItemColleciton = Backbone.Collection.extend({
  url: '/load-items',
});

var Group = Backbone.Model.extend({
  items: new ItemCollection(),
  initialize: function() {
    // load the groups items as the group is initialized
    this.items.fetch({data:{groupID:this.id}});
  }
});

Alternatively, if you have fewer models, you may wish to load them all at once, and use filtering to populate the groups. Something like this ...

var Item = Backbone.Model.extend({});
var ItemColleciton = Backbone.Collection.extend({
  url: '/load-groups',
});

var Group = Backbone.Model.extend({
  initialize: function() {
    // load the groups items as a subset of the already loaded group collection
    this.items = new ItemCollection(allItems.filter(function(item) {
      return item.GroupID = this.id;
    }, this));
  }
});

// in your router init ...
var allItems = new ItemCollection();
allItems.fetch();

The above are just example approaches. What I found after using backbone for a while, is that it's really open to interpretation, and can be implemented quite differently to solve different problems.

You may also wish to check out backbone relational . I've not used it myself, but believe it has added support for mapping relationships between models and collection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM