主干模型/集合中的Javascript范围界定问题

Javascript Scoping Issue in Backbone Model / Collection

本文关键字:范围 Javascript 问题 模型 集合      更新时间:2023-09-26

我使用的是树结构,所以每当我想从树叶到树干时,我都需要做一些漂亮的wonkey查找,但我基本上是在尝试创建一个函数,我可以将函数传递给它,并将/call/bind/应用于原始上下文,这样我就可以看到我原来拥有的变量。一个解释会很棒。

layerListView = Backbone.Marionette.CollectionView.extend({    
    updateSelectedModelsInTree: function () {
        var col = myApp.request('someOtherCollection');
        this.collection.startFromLeaves(function (m) {
            this.updateSelected(m);
            // col is undefined in here
        }, this);
    }
});
layerCollection = Backbone.Collection.extend({
    startFromLeaves: function (doToModel, context) {
        if (!this.models) return;
        for (var i = this.models.length - 1; i >= 0; i--) {
            var model = this.models[i],
                tag = this.models[i].get('tag');
            if (tag == 'branch') this.startFromLeaves(arguments);
            doToModel.call(context, model);
        }
    }
});

所以我被困在这里,我所想做的就是能够看到传递到startFromLeaves的top函数内部的col变量。我不知道如何使用call/bind/apply,但我猜我的上下文是导致一切失败的原因。

查看underscore.js 上的绑定函数

这允许您传递一个具有此上下文集的函数。例如,你可以做

updateSelectedModelsInTree: function () {
    var col = myApp.request('someOtherCollection');
    this.collection.startFromLeaves(_.bind(function (m) {
        this.updateSelected(m);
        // col is undefined in here
    }, this));
}

函数中的"this"现在将始终是包含"updateSelectedModelsInTee"的"this"