Search code examples
backbone.js

Automatically sort after adding model in backbone collection


I want to be able to sort the data after adding a model to the collection. If I don't apply silent:true the collection will be render but everything doubles up. Is there another way?

I'm rendering the template on initialize function and rendering the collection sub view after reset.


Solution

  • Got it to work though I'll answer my question because i'm not sure if this is the best answer so comments are welcome.

    on my view:

        initialize : function(){
            this.$el.html( this._template );
            this.collection.bind('reset', this.LoadItems, this);
            this.collection.bind('add', this.AddOneItem, this);
            $("#settings-category").trigger("create");  
        },
    
        LoadItems : function(){
            this.collection.each(function(model){
                this.view = new CurrentCategoryView({model : model});
                 $("#currentCategoryListContainer").append(this.view.render().el);
            });
            $("#currentCategoryListContainer").listview("refresh");
        },
    

    this results to a normal rendering of DOM elements but if i use sort which eventually triggers a reset my function doesn't include the code above so the result is that it doesn't clear up the DOM elements and proceed on adding more elements causing the Collection models to be rendered twice. So here is my solution.

    $("#currentCategoryListContainer").empty();
    this.collection.sort();
    

    In this way i clears up the already occupied DOM to make way for the new Items( sorted items) to be rendered.