Giter VIP home page Giter VIP logo

backbone.groupedcollection's Introduction

Backbone GroupedCollection

Built at Teambox

Build Status

Backbone GroupedCollection is for creating dynamic data strcutures like this.

grouped-collection

In which you have a collection and you want to group the models in the collection into an arbitrary number of groups, based on attributes of the models.

Using this library allows you to do some things that could get quite complicated if not, for example:

  • Sorting groups and models in groups seperately
  • Appending new models to the right group automatically
  • Adding and removing groups when models are added or removed
  • Creating a dynamic tree that responds to change events in the models

How does it work?

Backbone.buildGroupedCollection recieves a base collection and a groupBy function. It returns a collection of models (groups). Each of the groups has it's group identifier as the id, and a special property vc which is a Backbone.VirtualCollection of the models that belong in the group.

It works well with Marionette or stand-alone.

var animals = new Backbone.Collection([
  {name: 'cat', color: 'black'},
  {name: 'dog', color: 'black'},
  {name: 'bird', color: 'red'}
]);

var grouped_animals = Backbone.buildGroupedCollection({
  collection: animals
, groupBy: function (animal) {
    return animal.get('color');
  }
});

The structure looks something like this:

  • GroupCollection
    • Group (black)
      • Animal (cat)
      • Animal (dog)
    • Group (red)
      • Animal (bird)

And the structure adapts itself constantly to changes in the base colleciton.

grouped_animals.pluck('id'); // ['black', 'red']
grouped_animals.get('black').vc.length; // 2
grouped_animals.get('red').vc.length; // 1

// adding elements
animals.add({name: 'dinosaur', color: 'green'});
grouped_animals.pluck('id'); // ['black', 'red', 'green']
grouped_animals.get('green').vc.at(0) === animals.findWhere({name: 'dinosaur'}); // true

// removing elements
animals.remove(animals.findWhere({name: 'cat'}));
grouped_animals.pluck('id'); // ['black', 'green']

Recursive Grouping

Somtimes you want to make sub-groups, or infinitely nested groups. For example, you have a shopping list that you want grouped by store, and then within each store, by item type.

var grouped_shopping_list = Backbone.buildGroupedCollection({
  collection: shopping_list,
, groupBy: groupByShop
, GroupModel: Backbone.Model.extend({
    initialize: function (options) {
      // options.id is the group id
      // options.vc is the  virtual collection
      this.grouped_vc = Backbone.buildGroupedCollection({
        collection: options.vc
      , groupBy: groupByItemType
      })
    }
  })
});

// the items of type "office supplies" from the store "home depot" will be accesible at

grouped_shopping_list.get('home_depot').grouped_vc.get('office_supplies') // retutns a virtual collection

Options

collection

The base collection.

groupBy

The function that defines the grouping. It recieves a model as the argument, and it must return the id of the group it belongs to.

close_with

The GroupCollection will continue listening to the base collection untill you call stopListening() on it. You can bind the lifespan of a grouped_collection to that of a marionette view by specifying a close_with option. (it can also be any event emitter that emits a close or destroy event)

GroupCollection

Specifies an alternative 'class' for the GroupCollection to have. It should extend from Backbone.Collection.

GroupModel

Specifes an alternative 'class' for the Groups to have. It should extend from Backbone.Model;

vc_options

Object passed to the virtual collections as options. Use this to configure comparators, etc.

Changelog

0.1.4 Added comparator option via @masylum
0.1.3 Change package name to allow publishing on npm
0.1.2 Add vc_options via @masylum. Fix close_with handling
0.1.1 Add listeners for 'change', 'remove' and 'reset' only once
0.1.0 Fixes groups not being deleted because a race condition with `VirtualCollection`
0.0.3 Fixes bug when changing a model failed to create a new Group
0.0.2 Add GroupCollection & Group options

License

The MIT License (MIT)

Copyright (c) 2013 Pedro [email protected]

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

backbone.groupedcollection's People

Contributors

marcelklehr avatar masylum avatar p3drosola avatar snags88 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

backbone.groupedcollection's Issues

Passing in filter as vc_options does not apply to grouped collection

I have a scenario in which I want to create a grouped collection from a real collection, but also apply a filter at the same time. For example, given the following collection:

var tasks = new Backbone.Collection([
  {name: 'bob', date: '02-19-2016', task: 'wash dishes'},
  {name: 'bob', date: '02-19-2016', task: 'read book'},
  {name: 'sally', date: '02-19-2016', task: 'walk the dog'},
  {name: 'bob', date: '02-20-2016', task: 'go to gym'},
]);

I want to only get Bob's tasks and group by date. Something like the following would be nice to do:

var groupedTasks = Backbone.buildGroupedCollection({
  collection: tasks,
  groupBy: function (task) {
    return task.get('date');
  },
  vc_options: {
    filter: function(task) {
      return task.get('name') === 'bob';
    }
  }
});

I looked around the code, and I think the reason why this doesn't work is because any filter options are overridden from this code.

My current solution is to first create a virtual collection with the filter I want, then pass it in as the collection for the grouped collection:

var virtualCollection = Backbone.VirtualCollection(tasks, {
  filter: function(task) {
    return task.get('name') === 'bob';
  }
});

var groupedTasks = Backbone.buildGroupedCollection({
  collection: virtualCollection,
  groupBy: function (task) {
    return task.get('date');
  }
});

Going to play around with this over the weekend, but figured I should raise an issue in case others are running into this.

Typo example front page

// removing elements animals.remove(animals.findWhere({name: 'cat'})); grouped_animals.pluck('id'); // ['black', 'green']

On the explanation of 'How does it work?'
In this code is it meant to read the animal as bird instead of cat that is removed?

Leaking virtualcollection listeners

  • close_with option is not being passed to group_collection.closeWith
  • close_with option is not being propagated to the virtualcollections, so they're leaking listeners

Recursive Grouping

Hello pedro,

I discovered your VirtualCollection recently when I was actually searching for a solution for grouping my collections, so I'm amazed again, that you already have a solution ready.
Or at least a part of my solution..

I'm trying to allow the user to group the collection by different properties, which the user can select. However, then I'd like to group the resulting items again per group, based on a different property.

So, for instance I'd like to group my shopping list by shops, and then again by item type, so I can quickly find all things that are in one place.

Is this possible? If so, how would you recommend going about implementing this?

Publish to NPM

Unlike Backbone.VirtualCollection, I can't seem to find this package on NPM. Has it been published?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.