1

I've search internet for days to find an optimized solution for having a live collection in backbone.js. think of a virtual room (e.g chat room) and I wanted to show who is in that room. right now I fetch collection each 2 sec and add new user (in my case player) to the list view, and it's working but I'm afraid of traffic and all of those useless ajax request that return nothing.

here is my backbone scripts:

App.players = new App.Collections.Players;
waitingUserList = new App.Views.WaitingPlayers({ collection: App.players });

setInterval(function() {
    App.players.fetch({
        success: function(collection) {
            collection.each(function(player) {
                if (player.get('added') == 0) {
                    player.set('added', 1);
                    player.save();
                }
            });
        },
    });
}, 2000);

$('div.waiting-list').append(waitingUserList.el);

and my php code (I'm using laravel 3):

public function get_index($gid)
{
    $players = Game::find($gid)->players()->get();
    if (!empty($players)) {
        return Response::eloquent($players);
    } else {
        return false;
    }
}

Is there any way that, when collection.fetch() called, it wait until some new record added to database, and then server respond to ajax request.

P.S. I don't want to use html5 websockets
P.S.S. this is my first backbone experience, so forgive me if I've been mistaken somewhere or said something foolish :D

thanks in advance

Behzadsh
  • 771
  • 1
  • 12
  • 28

1 Answers1

1

What you are doing is called polling. As you already mentioned, it doesn't scale very well. You should search for a comet like solution. It all depends on your backend. For example Apache doesn't do very well in this regard (Using comet with PHP?).

Depends on your needs, but I would recommend node.js and socked.io which implements web sockets and a fallback for older browsers. If you want to interact with your existing code use proxy on your main web servers.

Community
  • 1
  • 1
Rok Burgar
  • 919
  • 5
  • 7
  • 1
    I've found ratchet (http://socketo.me) and it seems to be what I need, I read the tutorials, but it was so complicated for me, so I think it's better to use node.js and socket.io since it has fallback for older browser as you mentioned. thank you for your answer – Behzadsh Apr 20 '13 at 20:53