Checking for an empty collection in backbonejs

I am developing a one-page application with requirejs and backbonejs that includes fetching records from a db table and displaying them. I do it with the click of a button. I assume that I unnecessarily retrieve models from the server several times with the click of a button.

What I want is that after I get the collection model, it should not return when the button is clicked again. Any changes / additions that I make during the assembly are related to checking the server, so I can save the last list without thinking about retrieving all the models from the server when I click this button.

So I need to check if the collection is empty or not before choosing models. something like that:

if(window.invoices.isEmpty()) { window.invoices.fetch({success:function(model){ model.each(self.addOne,self); }}); } else { window.invoices.each(self.addOne,self); } 

Please shed some light if I am fundamentally wrong here.

+4
source share
1 answer

You can use the length method.

window.invoices.length == 0


However, I'm a little unsure what you are trying to do with model.each(self.addOne, self) . When you select a collection, Backbone will create models from the returned JSON and populate the collection for you.

+6
source

All Articles