backbone.js - 了解 Backbone 集合上的 _.each

标签 backbone.js underscore.js

警告:我是一个 Backbone 新手。

我正在迭代我集合中的所有模型并渲染它们。然而,很简单,我想确保我很好地理解这是如何工作的。这是我所拥有的 -

模型:

File = Backbone.Model.extend({});

收藏
Folder = Backbone.Collection.extend({ model: File });

模型 View
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") }));
    }   
})

集合 View
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); <--???
    }
});

这工作得很好。我的问题是关于 FolderView 中的 _.each。为什么我必须将 this 传回我的每个循环?
如果我不传递这个,它指的是我的窗口对象而不是我的集合。我知道有必要通过它,我只是不知道为什么。

最佳答案

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

Iterates over a list of elements, yielding each in turn to an iterator function. The iterator is bound to the context object, if one is passed. Each invocation of iterator is called with three arguments: (element, index, list). If list is a JavaScript object, iterator's arguments will be (value, key, list). Delegates to the native forEach function if it exists.

underscore docs#each


默认上下文是窗口对象。通过设置 this作为上下文,您正在制作 this在函数映射到 this函数被调用的地方。
有关此主题的引用,请参阅以下内容:
  • A bit about function contexts
  • underscore source for _.each
  • ForEach docs
  • Strict vs non-strict context
  • 关于backbone.js - 了解 Backbone 集合上的 _.each,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18254300/

    相关文章:

    jquery - BackboneJS $el.html() 似乎没有任何效果

    javascript - 从对象数组中提取数据(问题稍微复杂)

    javascript - 下划线模板错误 = 未捕获的语法错误 : Unexpected token ILLEGAL

    javascript - 如何在 Javascript 中使用 takeWhile 函数?

    javascript - backbone.js:我将如何使用 backbone.js 处理从客户端向服务器发送登录数据

    javascript - 主干触发事件变量

    javascript - 来自终端的 npm install 错误

    JavaScript/Backbone.js 布局管理器

    javascript - 如何在一个 View 中获取多个集合

    javascript - 排序数组中的公共(public)值段