简体   繁体   English

如何绑定到以功能为参数的功能

[英]How to bind to function that takes function as parameter

I have the following I want to pass a parameter from a higher context which is onDeselectionStyle to the eachlayer method. 我有以下内容,我希望将参数从onDeselectionStyle的更高上下文传递给eachlayer方法。

clearAll: function(){
        this.map.eachLayer(function(layer){
            if(layer.options.clicked == true){
                layer.options.clicked == false;
                layer.setStyle(this.onDeselectionStyle);
            }
        })
    }

I know that I need to bind this to the function but I don't know how to do it in this format. 我知道我需要将此绑定到函数,但是我不知道如何以这种格式进行操作。 Thank you 谢谢

Option 1 选项1

You can use the prototypical bind method on the function declaration: 您可以在函数声明中使用原型绑定方法:

clearAll: function () {
    this.map.eachLayer(function (layer) {
        if (layer.options.clicked == true) {
            layer.options.clicked == false;
            layer.setStyle(this.onDeselectionStyle);
        }
    }.bind(this))
}

Option 2 选项2

If you are using ES6, you can use an arrow function which will use the parent scope: 如果使用的是ES6,则可以使用箭头功能,该功能将使用父作用域:

clearAll: function () {
    this.map.eachLayer(layer => {
        if (layer.options.clicked == true) {
            layer.options.clicked == false;
            layer.setStyle(this.onDeselectionStyle);
        }
    })
}

Option 3 选项3

This one doesn't really have much to do with binding context, but you can store the scope in an accessible variable you can use later: 这实际上与绑定上下文没有多大关系,但是您可以将范围存储在一个可访问的变量中,以供以后使用:

clearAll: function () {
    var that = this;
    this.map.eachLayer(function(layer) {
        if (layer.options.clicked == true) {
            layer.options.clicked == false;
            layer.setStyle(that.onDeselectionStyle);
        }
    })
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM