Reputation: 6976
I am writing a search function at the moment for my Backbone application, the idea is that a user can enter a string and the app will search for and return any matching models where the string appears in any of its attributes. So far I have the following,
view function run on keyup,
this.results = this.collection.search(letters);
This runs the following code located in the collection,
search: function( filterValue ) {
filterValue = filterValue.toLowerCase();
var filterThroughValue = function(data) {
return _.some(_.values(data.toJSON()), function(value) {
console.log(value);
if(value != undefined) {
value = (!isNaN(value) ? value.toString() : value);
return value.toLowerCase().indexOf(filterValue) >= 0;
}
});
};
return App.Collections.filterCollection = this.filter(filterThroughValue);
}
However running this I get the following error,
Uncaught TypeError: undefined is not a function
this error is shown as being the line return value.toLowerCase().indexOf(filterValue) >= 0;
and this error gets returned whether or not I use a string I know exists in a model of the collection.
Is there a fix for this, or a better way of searching and returning only models that have models that contain the search string?
Upvotes: 0
Views: 625
Reputation: 762
Since you just want a string representation of value, you can probably just check if value has a toString method. Note that String also has a toString method, so this will work if value is a String.
return _.some(_.values(data.toJSON()), function(value) {
if(value && value.toString) {
return value.toString().toLowerCase().indexOf(filterValue) >= 0;
}
return false;
}
Upvotes: 1