简体   繁体   中英

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.

Am I doing something wrong, or is there a way to make dropHandler bind to each index of the elements in the list?

The drop binding is defined as follows

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. 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()) }">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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