I have a notifications model for notifications
// MODEL
NotificationModel = App.BB.Model.extend({
defaults : {}
});
// COLLECTION
NotificationCollection = App.BB.Collection.extend({
model: NotificationModel,
url: '/notifications',
initialize : function() {
var me = this;
me.fetch();
}
});
The collection is fetching from the server correctly and has the following fields (id, read) where read is true or false.
How can I get the total number count of items that are read == false? ... Unread item count?
Thanks
A structured solution would be to create these methods in your collection:
read: function() {
return this.filter(function(n) { return n.get('read'); });
},
unread: function() {
return this.filter(function(n) { return !(n.get('read')); });
}
If you need the count, you can just add .length
to the end of the method.
Using the underscore's filter
method and general JavaScript .length
schould do it.
Backbone's documentation has an example of filter
, you just need to return read equals false.
var unread = Notes.filter(function(note) {
return note.get("read") === false;
}).length;
submitting from my mobile phone, sorry for the brief answer
Backbone Collection's where
method might be of use.
var read = this.where({ read: true });
var unread = this.where({ read: false });
This doesn't work if read
isn't true
or false
-- in that case, you should use filter
as the other answers suggest.