简体   繁体   English

淘汰赛中的惰性评估对象绑定问题

[英]Issue with lazy evaluated object binding in knockout

I have the following binding 我有以下绑定

<ul data-bind="foreach: tubeRack.containers">
    <li data-bind="drop: { handler: $parent.dropHandler.bind(null, $index()) }">
    ...

And the problem is that the dropHandler.bind apparently only gets evaluated when used in the binding, which makes $index() always return the index of the last element. 问题是dropHandler.bind显然仅在绑定中使用时才被求值,这使得$index()始终返回最后一个元素的索引。

Am I doing something wrong, or is there a way to make dropHandler bind to each index of the elements in the list? 我是在做错什么,还是有办法使dropHandler绑定到列表中元素的每个索引?

The drop binding is defined as follows drop绑定定义如下

ko.bindingHandlers.drop = {
    init: function (element, valueAccessor, allBindingsAccessor, viewModel, context) {
        var self = this;

        var options = valueAccessor();
        self.accept = options.accept || _.constant(true);
        self.handler = options.handler;

        $(element).droppable({
            tolerance: 'pointer',
            accept: function (draggable) {
                return self.accept(dragData);
            },
            drop: function(evt, ui) {
                self.handler(dragData);
            }
        });
    }
};

答案是,绑定this保持了愚蠢的引用,并对其设置了处理程序功能,导致handler变量被覆盖。

Since index() belongs to the foreach, as you've identified correctly, it will only ever have the correct value during the evaluation of that foreach. 由于index()属于foreach,因此您已正确识别,因此在评估该foreach时它只会具有正确的值。 Thus, I suggest the following workaround to force a timely evaulation. 因此,我建议采用以下解决方法来强制及时进行评估。 I couldn't test it, unfortunately, but it should at least be able to serve as a hint: 不幸的是,我无法对其进行测试,但是它至少应该能够作为提示:

<li data-bind="drop: { handler: (function(idx) { $parent.dropHandler.bind(null, idx); })($index()) }">

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

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