forked from homeslicesolutions-zz/backbone-collection-search
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackbone-collection-search.js
executable file
·86 lines (67 loc) · 2.23 KB
/
backbone-collection-search.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
// Backbone.Collection.search v0.2.1
// by Joe Vu - [email protected]
// For all details and documentation:
// https://github.com/homeslicesolutions/backbone-collection-search
;(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define(['underscore', 'backbone'], factory);
} else if (typeof exports === 'object') {
module.exports = factory(require('underscore'), require('backbone'));
} else {
factory(root._, root.Backbone);
}
}(this, function (_, Backbone, Fuse) {
// Extending out
_.extend(Backbone.Collection.prototype, {
//@ Default Matcher - may be overwritten
matcher: function(needle, haystack) {
if (!needle || !haystack) return;
needle = needle.toString().toLowerCase();
haystack = haystack.toString().toLowerCase();
return haystack.indexOf( needle ) >= 0;
},
//@ Search function
search: function(keyword, attributes) {
// If collection empty get out
if (!this.models.length) return;
var keys = _.result(this, 'searchable', []);
// Filter
var matcher = this.matcher;
var results = this.filter(function( model ) {
return !_.every( keys, function( attribute ) {
return !matcher( keyword, model.get( attribute ) );
});
});
// Instantiate new Collection
var collection = new Backbone.Collection( results );
collection.searching = {
keyword: keyword,
attributes: keys
};
collection.getSearchQuery = function() {
return this.searching;
};
// Cache the recently searched metadata
this._searchResults = collection;
// Async support with trigger
var that = this;
var t = setTimeout(function(){
that.trigger('search', collection);
clearTimeout(t);
}, 10);
// For use of returning un-async
return collection;
},
//@ Get recent search query
getSearchQuery: function() {
return this.getSearchResults() && this.getSearchResults().getSearchQuery();
},
//@ Get recent search results
getSearchResults: function() {
return this._searchResults;
},
//_Cache
_searchResults: null
});
return Backbone;
}));