javascript - Backbone.js Collection View 渲染重复项

标签 javascript backbone.js

在我的 Backbone.js 应用程序中,我需要能够在集合中的现有项之间插入新项。到目前为止,我在网上找到的示例似乎都假设新项目应该附加到集合的末尾。这对我的目的不起作用,所以我选择在添加新项目时重新呈现整个集合。

但是,原始项目并没有从 View 中删除;相反,一组重复的项目被附加到列表的末尾。我可以通过使用 jQuery 在渲染之前清除项目来解决这个问题,但这似乎是错误的。

这是我现在拥有的:

Item = Backbone.Model.extend({
    price: null,
});

Items = Backbone.Collection.extend({
    model: Item, 
    initialize: function () {
      this.add(new Item({ price: '$0.50' }));
      this.add(new Item({ price: '$0.60' }));
      this.add(new Item({ price: '$0.70' }));
    }
});

ItemView = Backbone.View.extend({
    tagName: 'li',
    initialize: function () {
      this.model.bind('change', this.render, this);
    },

    render: function () {
      var item_template = _.template($('#item-template').html(), { item: this.model }); 
      this.$el.html(item_template);
      return this;
    },

    events: {
      "click .copy-item": "copyItem",
    },

    copyItem: function (event) {
      var index = itemlistview.collection.indexOf(this.model);
      itemlistview.collection.add(new Item, { at: index + 1 });
    },
});

ItemListView = Backbone.View.extend({
    el: '#item-rows',
    initialize: function () {
      _.bindAll(this);
      this.collection = new Items();
      this.collection.bind('add', this.render);
      this.render();
    },
    render: function () {
      // It works if I uncomment the line below
      //$('.item-row').remove();
      var self = this;
      this.collection.each(function (item) {
        self.$el.append(new ItemView({ model: item }).render().el);
      });
      return this;
    },
});

var itemlistview = new ItemListView;

这是一个 jsFiddle这说明了问题。

有没有更好的方法来处理这个问题?

最佳答案

在重新渲染整个内容时,您确实需要清除旧的渲染输入。

http://jsfiddle.net/Zk9NX/8/

改变项目 ListView

ItemListView = Backbone.View.extend({
    el: '#item-rows',
    initialize: function () {
      _.bindAll(this);
      this.collection = new Items();
      this.collection.bind('add', this.render);
      this.render();
    },
    render: function () {
      var self = this;
      this.$el.empty()
      this.collection.each(function (item) {
        self.$el.append(new ItemView({ model: item }).render().el);
      });
      return this;
    },
});

关于javascript - Backbone.js Collection View 渲染重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9602039/

相关文章:

ios - PhoneGap 和 Backbone Ajax 调用需要很长时间

javascript - 如何使用 requestAnimationFrame 为 Canvas 中的图像设置动画?

javascript - 合并两个单独的 JavaScript 对象的属性的最佳方法是什么?

javascript - 用切片复制数组时的奇怪行为

javascript - 将可编辑 Select2Cell 的值替换为已从数据库呈现的 Backgrid 表中的文本(链接到值)

javascript - 在 backbone.js 中单击链接时强制刷新页面

javascript - Meteor 0.8.0 blaze 中的模板渲染回调

javascript - [jQuery/javascript] : find a couple of items (2) in an array

javascript - 比较在 javascript 中不使用 toLocaleDateString() 的日期?

javascript - 我的下划线模板不会在我的主干应用程序中呈现我的集合