Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/backbone.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/amazon-s3/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Collections backbone.js:向集合中添加元素,而不重新呈现所有集合_Collections_Backbone.js - Fatal编程技术网

Collections backbone.js:向集合中添加元素,而不重新呈现所有集合

Collections backbone.js:向集合中添加元素,而不重新呈现所有集合,collections,backbone.js,Collections,Backbone.js,我有一个从集合中呈现自身的视图: render: function() { $(this.el).html(JST['templates/menu']({collection: this.collection })); $('#nav').html(this.el); } 在视图初始值设定项中,我将集合的add事件绑定到视图的render函数上: initialize: function() { this.render(); var self = t

我有一个从集合中呈现自身的视图:

render: function() {

    $(this.el).html(JST['templates/menu']({collection: this.collection }));
    $('#nav').html(this.el);     
}
在视图初始值设定项中,我将集合的add事件绑定到视图的render函数上:

initialize: function() {
    this.render();
    var self = this;
    this.collection.bind("add", function(event){
        self.render();
    });
}
在应用程序的其他地方,我向集合中添加了一项

bookSubscription_collection.add(model);
该代码的问题是,如果向集合中添加一个新项,则集合中的所有项都将重新呈现


有没有一种方法可以在不重新渲染所有其他项的情况下将新项添加到集合中,而只渲染新项?

与其将集合的添加事件绑定到渲染函数,不如将其绑定到接受所添加模型的其他函数,并使用添加的模型中的数据修改DOM。

这是我所做工作的简化版本
reset
将所有模型添加到UI中,
add
将单个模型添加到UI中
addAll
基本上有一个循环,为每个模型调用
addOne
。它可能会被优化得更好,但它工作得足够好

initialize: function() {
    _.bindAll(this, 'render', 'addOne', 'addAll');

    leads.bind('add', this.addOne, this);
    leads.bind('reset', this.addAll, this);
  },
  render: function() {
    this.addAll();
    return this;
  },
  addOne: function(model) {
    // add the model to HTML
  },
  addAll: function(options) {
    leads.each(this.addOne);
    return this;
  }

亚伯拉罕写了一个很好的例子。我也一直这样使用它

initialize: ->    
  self = @
  @model.bind "add", (task) ->
    $(self.el).append new app.TaskIndexItemView(model: task).render().el

但我认为addOne是更好的解决方案

为什么
self=@
?没有它也是一样的,您应该使用fat arrow=>作为绑定范围,而不是执行
$(self.el)
您可以执行
$(@el)
或者,如果您使用的是主干网0.9+,您应该使用
@$el
,它使用缓存的jQuery包装实例
this.el
如果添加ie.10模型,实际的HTML注入会调用一次吗?