Backbone Collection Sorting
Sort a Backbone collection using multiple sort fields, each of which may have its own sort direction.
by bryandowning
HTML
<script src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
<script src="http://documentcloud.github.com/backbone/backbone-min.js"></script>
CoffeeScript
# Color data
colors = [
h: 10
s: 10
l: 10
,
h: 10
s: 10
l: 20
,
h: 10
s: 20
l: 10
,
h: 10
s: 20
l: 20
,
h: 20
s: 10
l: 10
,
h: 20
s: 10
l: 20
,
h: 20
s: 20
l: 10
,
h: 20
s: 20
l: 20
,
h: 30
s: 10
l: 10
,
h: 30
s: 10
l: 20
,
h: 30
s: 20
l: 10
,
h: 30
s: 20
l: 20
]
# Color Model
class Color extends Backbone.Model
# Color Collection
class Colors extends Backbone.Collection
model: Color
# Determine sort order for hsl values
# value of dir (asc = true, desc = false)
sortInfo: [
type: 'h'
dir: true
,
type: 's'
dir: true
,
type: 'l'
dir: true
]
# Maintain order of models in collection
comparator: (color1, color2)->
# Loop over each object in @sortInfo
for sort in @sortInfo
# Continue to the next sort type if color1 is the same as color2
continue if color1.get(sort.type) is color2.get(sort.type)
# color1 is smaller than color2
if color1.get(sort.type) < color2.get(sort.type)
# Ascending
if sort.dir then return -1
# Descending
else return 1
# color1 is larger than color2
else
# Ascending
if sort.dir then return 1
# Descending
else return -1
# If we made it through all sort types
return 0
# Instantiate collection
colorCollection = new Colors colors
# Log colors to console in their sorted order
console.log color.toJSON() for color in colorCollection.models
console.log '---------- BREAK -----------'