理解关于骨干集合的_.each

neu*_*v33 5 backbone.js underscore.js

警告:我是骨干新手.

我正在迭代我的集合中的所有模型并渲染它们.但是,很简单,我想确保我很清楚这是如何工作的.这是我的 -

模型:

File = Backbone.Model.extend({});
Run Code Online (Sandbox Code Playgroud)

采集

Folder = Backbone.Collection.extend({ model: File });
Run Code Online (Sandbox Code Playgroud)

模型视图

FileView = Backbone.View.extend({
    initialize: function() {
       _.bindAll(this, 'render');
       this.render();
    },
    render: function() {
        this.template = _.template(document.getElementById("fileTemplate").innerHTML);
        this.$el.html(this.template({ fileName: this.model.get("FileName") }));
    }   
})
Run Code Online (Sandbox Code Playgroud)

的CollectionView

FolderView = Backbone.View.extend({    
    initialize: function () {
        _.bindAll(this, 'render');
        this.render();
    },
    render: function () {
        _(this.collection.models).each(function(file) {
            var fileView = new FileView({ model: file});
            this.$el.append(fileView.el);            
        },this); <--???
    }
});
Run Code Online (Sandbox Code Playgroud)

这完全没问题.我的问题是关于我的FolderView中的_.each.为什么我要通过回我的每一个循环?如果我没有传递,它指的是我的窗口对象而不是我的集合.我知道有必要通过它,我只是不知道为什么.

jmh*_*jmh 11

_.each(list, iterator, [context]) Alias: forEach

迭代元素列表,依次产生迭代器函数.迭代器绑定到上下文对象(如果传递了一个).每个迭代器调用都使用三个参数调用:(element,index,list).如果list是JavaScript对象,则迭代器的参数将是(value,key,list).如果存在,则委托原生forEach函数.

强调文档#the each

默认上下文是窗口对象.通过设置this为上下文,您将this在函数映射this中调用函数的调用位置.

有关此主题的信息,请参阅以下内容: