I'm using backbone.js, and I've got a collection with does fetch()
sometimes. I don't want to pass the option {add: true}
because of the way my subviews are created (the collection is looped over and each item is a new row appended to the current table). The one thing that I tried is just emptying the entire table and creating all new rows, but that is so slow since fetch()
is run pretty often (when the scroll gets close to the end of the table). It begins to lag.
I'm hoping there's an alternative where I can keep track of the new collection for appending purposes, yet have the whole collection as an entity. One possibility is creating a second collection and then adding it into the first, but I'm not sure how / if I should do that.
You could keep track of the current length of your collection, after new models are added to it use that as an offset to render the models from that point to the end of your collection.
UPDATE: just noticed this when I was looking through the underscore docs: http://documentcloud.github.com/underscore/#rest
To summarize it does this:
with this you just need to keep track of what your length was before additional items were added to the collection and then pass that into rest as the index.
I think creating a second collection of the new models is redundant. I'm trying to imagine your setup and here are some solution ideas.
Maybe one way you can do this is to change the way you do your subviews.
When you fetch() it resets your collection and it seems like you only need to work with the new models. In this case, using fetch with {add:true} sounds like a better solution. You mention that your subviews creation is looped, and I imagine how when you reset the collection, having to loop through and create all new subviews can be slow. Can you change the subview creation so that corresponds to each model? Thus for each new model that is added into the collection, a subview is appended.
I'm imagining something like the Todo.js example. But the context of your problem might be totally off from what I'm seeing.
EDIT: How to access the new models you're adding to a collection
As per our discussion, I found this thread that confirms what I was thinking about the fetch success option and parameters.
In Backbone.js, after I perform a collection.fetch({'add':true}), how do I get the latest elements retrieved?
EDIT2: Full Working Backbone Example
This is the OUTPUT (Something like this):
Here is the HTML:
Here is the JS:
The following is the PHP server code - I use Slim PHP for my routing:
This was fun to work through. I learned something myself. Hope it helps! :-)