In backbone.js, how to update a view with new model data while keeping sorted order without rendering full

I have a view in backbonejs associated with a sorted collection.

I want to periodically update the collection with new models, but maintain a sorted order.

What is the best way to insert new models into a view without rendering it completely?

+3


source to share


2 answers


Collection.add , when it fires the "add" event, passes a hash of parameters that contains the "index" property, indicating where, if the collection is sorted through a comparator, the item is inserted.

Using the nth-child jQuery selector, you can insert the element where you want:



    $(function() {

        var ships = new Backbone.Collection();

        ships.comparator = function(ship) {
          return ship.get("name");
        };

        ships.on("add", function(ship, collection, options) {
            if (options.index === 0)
                $('ul#list').prepend("<li>Ahoy " + ship.get("name") + " at " + options.index + "!</li>");
            else
                $('ul#list li:nth-child('+ options.index +')').after("<li>Ahoy " + ship.get("name") + " at " + options.index + "!</li>");
        });

        ships.add([
            {name: "Flying Dutchman"},
            {name: "Black Pearl"}
        ]);

        ships.add({name: "Delaware"});

        ships.add({name: "Carolina"});

        ships.add({name: "America"});

    })

      

Example: http://jsfiddle.net/DRN4C/6/

+5


source


I don't have enough reputation to comment on another answer (I think this is a great answer and is just an addition), but you should note that as of 0.9.9, the hash options

will no longer include the property index

. From the changelog:

To improve the performance of adding, options.index will no longer be set in the event callback add

. collection.indexOf(model)

can be used to get the model index as needed.



In another answer, just replace options.index

withcollection.indexOf(ship)

+1


source







All Articles