0

I want my controller to send over multiple items as I find them. Can I call "res.json(item)" multiple times? I did a quick test and it seams to work a bit.

Background: I have a "collection" model that holds, among other things, an array of ids (~30). ForEach Id, I find the "ItemModel" with that id and send it to the backbonejs client to add it to a displayed list.

Since forEach is asynchronous, and the model.find method required a callback anyway I thought it would be wise to "res.json(item)" for each item, sending back ~30 frames.

The problem arises on the backbone.js side of things as ~30 socket frames are shown on chrome's network debug, but backbone only calls a single renderAdd event.

My renderAdd function works perfectly for a single addition, only appends, and has been tested by viewing another list of items)

In general, am I taking the correct approach or do I have a fundamentally flawed approach?

JHAWN
  • 399
  • 4
  • 18

1 Answers1

0

According to this QAs foreach is blocking, but the sync() method of BB.js is asynchronous. You can also try to use _.each of Undescore.js, which is a same but have a nicer syntax.

_.each([1, 2, 3], alert);

The real solution to your problem is to add multiple models at once:

ships.add([
  {name: "Flying Dutchman"},
  {name: "Black Pearl"}
]);
Community
  • 1
  • 1
Vadym Myrgorod
  • 456
  • 1
  • 4
  • 11