Skip to content

Commit 8eac3e0

Browse files
committed
Allow custom indexer keys.
1 parent 52cd4ba commit 8eac3e0

File tree

2 files changed

+32
-2
lines changed

2 files changed

+32
-2
lines changed

src/indexer.js

+6-2
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
}
1010

1111
Model.Indexer.prototype.add = function(model) {
12-
this.get(model.get(this.attribute)).add(model)
12+
this.get(this.toKey(model)).add(model)
1313
model.on("change:" + this.attribute, this.change, this)
1414
}
1515

@@ -23,7 +23,11 @@
2323
}
2424

2525
Model.Indexer.prototype.remove = function(model) {
26-
this.get(model.get(this.attribute)).remove(model)
26+
this.get(this.toKey(model)).remove(model)
2727
model.off("change:" + this.attribute, this.change, this)
2828
}
29+
30+
Model.Indexer.prototype.toKey = function(model) {
31+
return model.get(this.attribute)
32+
}
2933
})(Model);

test/tests/indexer_test.js

+26
Original file line numberDiff line numberDiff line change
@@ -37,3 +37,29 @@ test("manages its index correctly", function() {
3737
equal(index.get(2).length, 0, "model is removed from the index")
3838
equal(story2._events["change:project_id"].length, 0, "Indexer callbacks are cleaned up")
3939
})
40+
41+
test("with a custom #toKey", function() {
42+
var Story = Model("story")
43+
44+
var story1 = new Story({ when: new Date(2012, 2, 3) })
45+
var story2 = new Story({ when: new Date(2012, 2, 14) })
46+
var story3 = new Story({ when: new Date(2012, 2, 3) })
47+
48+
var index = new Model.Indexer(Story.collection, "when")
49+
50+
index.toKey = function(model) {
51+
var when = model.get("when")
52+
return [when.getFullYear(), when.getMonth(), when.getDate()].join("-")
53+
}
54+
55+
Story.collection.add(story1)
56+
Story.collection.add(story2)
57+
Story.collection.add(story3)
58+
59+
equal(index.get("2012-2-3").length, 2)
60+
equal(index.get("2012-2-14").length, 1)
61+
62+
ok(index.get("2012-2-3").first() === story1)
63+
ok(index.get("2012-2-3").last() === story3)
64+
ok(index.get("2012-2-14").first() === story2)
65+
})

0 commit comments

Comments
 (0)