Backbone附加到列表视图而不是替换它

时间:2013-08-06 17:08:44

标签: backbone.js

我正在使用Wordpress和Backbone.js制作单页网站,我在获取新数据时遇到了问题。它只是将DOM元素添加到容器el而不是替换它们。集合正确更新,因为我可以看到它在控制台中有适量的元素。

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;
  });

});

1 个答案:

答案 0 :(得分:4)

你需要清除你的collectionView的$ el! :)

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

这应该可以解决问题。