forked from mpneuried/backlunr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
backlunr.mixin.js
103 lines (79 loc) · 2.4 KB
/
backlunr.mixin.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
Backbone.LunrMixin = {
lunroptions: {
fields: []
},
initialize: function(models, options) {
this._lunrInitialize();
this.on('add', _.bind(this._lunrAdd, this));
this.on('remove', _.bind(this._lunrRemove, this));
this.on('change', _.bind(this._lunrChange, this));
},
_lunrInitialize: function() {
var collection = this;
this._lunrFields = [];
this._lunrIndex = lunr(function() {
var that = this;
var opt;
if (_.isFunction(collection.lunroptions)) {
opt = collection.lunroptions(opt);
} else {
opt = _.extend({}, collection.lunroptions);
}
this.ref('cid');
_.each(opt.fields, function(field) {
collection._lunrFields.push(field.name);
that.field(field.name, _.omit(field, ['isID', 'name']));
});
});
},
_lunrAdd: function(model) {
this._lunrIndex.add(this._lunrPrepareModel(model));
},
_lunrRemove: function(model) {
var _model;
_model = model.toJSON();
_model.cid = model.cid;
this._lunrIndex.remove(_model);
},
_lunrChange: function(model) {
this._lunrIndex.update(this._lunrPrepareModel(model));
},
_lunrPrepareModel: function(model) {
var _model = model.toJSON();
_model.cid = model.cid;
_.each(this._lunrFields, function(field) {
if (_.isUndefined(_model[field])) {
_model[field] = '';
} else {
_model[field] = _model[field].toString();
}
});
return _model;
},
reset: function(models, options) {
var that = this;
this._lunrInitialize();
this.each(function(model) {
that._lunrAdd(model);
});
},
processTerm: function(term) {
return term;
},
search: function(term, raw) {
var that = this;
var _lunrRes = this._lunrIndex.search(this.processTerm(term));
if (raw) {
return _lunrRes;
}
var _res = _.map(_lunrRes, function(res) {
return that.get(res.ref);
});
_res.toJSON = function(options) {
return _.map(this, function(model) {
return model.toJSON(options);
});
};
return _res;
}
};