Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone.js: After doing Fetch(), render only the new models

I have a Collection App.listingList where subsequent fetch() are called with add:true.

App.listingList.fetch({
        data: {some:data},
        processData: true,
        add: true
});

Problem: How can the newly added models have their views rendered, without re-rendering the views of the existing models. This means I cannot do:

this.collection.each( function(listing, index) {
    new ListingMarkerView({ model:listing }).render();
}, this);

Attempt #1

Rendering the View on the collection's add event, I cannot figure out a way to access the new models to render

ListingListView = Backbone.View.extend({

    initialize: function() {
        this.collection.bind('add', this.renderNew, this);
    },

    render: function() {
        console.log('render ListingListView');
        this.collection.each( function(listing, index) {
            new ListingMarkerView({ model:listing }).render();
        }, this);
        return this;
    },

    renderNew: function() {
        // How do I grab the new models?
        new ListingMarkerView({ model:listing }).render(); // wont work
        return this;
    }
});

Attempt #2

I tried having a second Collection to do the subsequent fetch on, and compare the models of both collections using underscore.js's _.without(), but the array returned still contains the elements found in the 2nd array passed as the parameter. Using _difference() also returned the same array passed as the first array.

App.listingListNew.fetch({
        data: {some:data},
        processData: true,
        success: function() {
            console.log(App.listingListNew.models);
            console.log(App.listingList.models);
            console.log(_.without(App.listingListNew.models, App.listingList.models));
            console.log(_.difference(App.listingListNew.models, App.listingList.models));
        }
});

console.log Output

Since I passed in 2 identical arrays into _.difference() and _.without(), the output should be []. But it isnt :/ Maybe because cid is different, so every one of them are treated as unique?

enter image description here

like image 483
Nyxynyx Avatar asked Sep 29 '12 19:09

Nyxynyx


1 Answers

When you do a collection.bind('add', this.renderNew, this); it automatically passes the added model to your method as an argument.

Include the argument in your method and you should have access to the new model.

renderNew: function(newModel) {
    new ListingMarkerView({ model:newModel }).render();
    return this;
}
like image 130
jmk2142 Avatar answered Sep 28 '22 13:09

jmk2142