Batman.SetIndex is a grouped collection of items derived from a
Batman.Set filled with
Batman.Objects. It extends
Batman.Enumerable, so it inherits methods from them, too. In short, a
SetIndex tracks its base
Set and contains "buckets" of items from that
Set, grouped by the provided key.
test 'SetIndex groups items by values', -> batarang = new Batman.Object(name: "Batarang", type: "ranged") fists = new Batman.Object(name: "Fists", type: "melee") weapons = new Batman.Set(batarang, fists) # Three ways to create a SetIndex: weaponsByType1 = weapons.indexedBy('type') weaponsByType2 = weapons.get('indexedBy.type') weaponsByType3 = new Batman.SetIndex(weapons, 'type') # additions to the base Set are tracked by the SetIndex grappleGun = new Batman.Object(name: "Grapple Gun", type: "ranged") weapons.add(grappleGun) for setIndex in [weaponsByType1, weaponsByType2, weaponsByType3] equal setIndex.get('ranged').get('length'), 2 equal setIndex.get('melee').get('length'), 1 deepEqual setIndex.get('ranged').mapToProperty('name'), ["Batarang", "Grapple Gun"] deepEqual setIndex.toArray(), ["ranged", "melee"]
Using a Batman.SetIndex
SetIndex is a proxy of a
Set, the easiest way to make one is to use
weaponIndex = weapons.indexedBy('type')
weaponIndex is a
SetIndex. To find matches for a
meleeWeapons = weaponIndex.get('melee')
meleeWeapons is a
Batman.Set containing items where
type = "melee".
You can also make
SetIndexes in view bindings:
<ul> <li data-foreach-meleeweapon='weapons.indexedBy.type.melee'> <!-- will render items where type="melee" --> </li> </ul>
SetIndexes are observable proxies of their underlying
Sets. So, when the
Set is changed (ie, items are added, removed, or modified):
SetIndexis automatically updated by batman.js
- Any view bindings or accessors depending on the
SetIndexis made with a
key. Items in the
baseset will be grouped according to their value for
key. The resulting
base, so any items added to the
baseare also added (and indexed) in the
Batman.Setof items whose indexed
value. It returns an empty set if no items match
value, but if any matching items are added to the
baseset, they will also be added to this set.
Returns an array with the distinct values of
keyprovided to the constructor.
func(key, group)for each group in the SetIndex.