So I have a collection in Backbone for a list of events. This collection has a method on it which filters the list based on a list of categories passed to it.
var Events = Backbone.Collection.extend({
model: Event,
url: settings.events_url,
filtered: function(checked) {
return this.filter(function(e) {
if ($.inArray(e.get('category').name, checked) >= 0) {
return true;
} else {
return false;
}
});
}
});
What I need to be able to do is convert this filtered collection to JSON, the same way you would do the collection as a whole.
var events = new Events();
events.toJSON();
However, because the filtered collection is no longer an actual collection, but rather a list of models, I don't have the .toJSON() method available to me. Is there a way to convert my filtered collection to a real collection? Or is there an easier way to convert it to JSON?
Thanks!
The constructor for a collection can take a list of models as an argument so:
var events = new Events();
var filteredEvents = new Events(events.filtered(true));
console.log(filteredEvents.toJSON());