简体   繁体   English

KnockoutJS自定义绑定范围问题

[英]KnockoutJS custom binding scoping issue

I have a custom binding that overrides knockout's click handler like so: 我有一个自定义绑定,它像这样覆盖替代敲除程序的单击处理程序:

var originalInit = ko.bindingHandlers.click.init,
    originalUpdate = ko.bindingHandlers.click.update;

ko.bindingHandlers.click = {
    init: function(element, valueAccessor, allBindingsAccessor, viewModel, context) {

        var wrappedValueAccessor = function() {
            return function(data, event) {
                var disabled = allBindingsAccessor.get('disabled');
                var clickResult = valueAccessor().call(viewModel, data, event);

                if (clickResult && typeof clickResult.always === "function") {
                    $(element).attr('disabled','disabled');
                    clickResult.always(function(){
                        $(element).removeAttr('disabled');
                    });
                }

            };

        };

        originalInit(element, wrappedValueAccessor, allBindingsAccessor, viewModel, context);
    },
    update: originalUpdate
};

Find the fiddle here: http://jsfiddle.net/92q5vgfp/ 在这里找到小提琴: http : //jsfiddle.net/92q5vgfp/

The problem is when I try to access allBindingsAccessor inside the click from the chrome debugger, it's not available. 问题是,当我尝试从Chrome调试器单击时访问allBindingsAccessor时,它不可用。

However, if i have a console.log(allBindingsAccessor), chrome's debugger can see it. 但是,如果我有console.log(allBindingsAccessor),chrome的调试器可以看到它。

Update So, while I was writing this, we tried a random thing, which was to assign the function to a variable before returning it. 更新因此,当我写这篇文章时,我们尝试了一个随机的事情,那就是在返回变量之前将函数分配给变量。 That worked. 那行得通。 Don't know why or how. 不知道为什么或如何。

var wrappedValueAccessor = function() {
            var test = function(data, event) {
                ...
            };
            return test;
};

So that's my question, WHY would assigning the function to a local var and returning it work but not directly returning it? 这就是我的问题,为什么要将该函数分配给本地var并使其返回工作状态,而不是直接将其返回? Is this a bug in chrome or expected (somehow)? 这是Chrome的错误还是预期的错误(以某种方式)?

In the linked snippet allBindingsAccessor is not accessed inside the inner function so v8 simply optimizes it out and don't add to the function closure. 在链接的代码段中,内部函数内部未访问allBindingsAccessor,因此v8只是对其进行了优化,而不添加到函数闭包中。 See crbug.com/172386 for more details. 有关更多详细信息,请参见crbug.com/172386

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

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