benpalmer
benpalmer

Reputation: 2088

Backbone appends to list view instead of replacing it

I am producing a single page website with Wordpress and Backbone.js, i have come into a problem with when i fetch new data. It simply adds DOM elements onto the container el rather than replacing them. The collection updates correctly as i can see it has the right amount of elements in the console.

var PostItem = Backbone.Model.extend();

var PostItems = Backbone.Collection.extend({
    model: PostItem,
    url: '/wp-admin/admin-ajax.php'
});

var postItems = new PostItems();

var PostView = Backbone.View.extend({ /* Model View */
  tagName : 'article',
  className : 'widget',
  template : _.template( $('#widgetPost').html() ),
  render: function(){
    var attributes = this.model.toJSON();
    this.$el.html( this.template( attributes ) ); 
    return this;
  }
});

var PostListView = Backbone.View.extend({ /* Collection View */
  el : '#content',
  initialize: function(){
    this.collection.on('add', this.addOne, this);
    this.collection.on('reset', this.addAll, this);
  },
  addOne: function(postItem){
    var postView = new PostView({ model : postItem });
    this.$el.append( postView.render().el );
  },
  addAll: function(){
    this.collection.forEach(this.addOne, this);
  },
  render: function(){
    this.addAll();
  },
});

var postListView = new PostListView({
  collection : postItems
});

$(function(){

  $('a#posts').click(function(){
    postItems.fetch({
      data: { 
        action: 'do_ajax', 
        fn: 'get_the_posts'
      }
    });
    return false;
  });

  $('a#pages').click(function(){
    postItems.fetch({
      data: { 
        action: 'do_ajax', 
        fn: 'get_the_pages'
      }
    });
    return false;
  });

});

Upvotes: 0

Views: 425

Answers (1)

Chris Camaratta
Chris Camaratta

Reputation: 2769

You need to clear out your collectionView's $el! :)

addAll: function(){
    this.$el.empty();
    this.collection.forEach(this.addOne, this);
}

This should do the trick.

Upvotes: 4

Related Questions