简体   繁体   English

自定义绑定动画不适用于foreach

[英]Custom binding animation not working on a foreach

Basically I'm trying to make a number to fade out, change, and fade back in. I used a custom binding that works fine on a regular element. 基本上,我试图使数字淡出,更改和淡入。我使用了对常规元素正常工作的自定义绑定。 But inside a foreach the fade out animation won't work, the number just hides. 但是在foreach中,淡出动画将不起作用,该数字只是隐藏起来。 This is the custom binding: 这是自定义绑定:

ko.bindingHandlers.slideTransition = {
  update: function(element, valueAccessor) {
    var value = valueAccessor();
    var valueUnwrapped = ko.utils.unwrapObservable(value);

    $(element).fadeOut('slow', function() {
        $(element).html(valueUnwrapped);       

        $(element).fadeIn('slow', function() {
            console.log('done');
        });
    });
  }
};

Working example: http://jsfiddle.net/brunomuller/qTvs9/6/ 工作示例: http : //jsfiddle.net/brunomuller/qTvs9/6/

First one is inside a foreach, getting the value from an array (fails), second one is binding the value itself (works). 第一个是在foreach内部,从数组中获取值(失败),第二个是绑定值本身(有效)。

Any idea why this is happening? 知道为什么会这样吗?

Your computed has an indirect dependency on Value , since you execute it before you put it in the returned array. 由于您在将计算Value放入返回的数组之前执行了计算Value ,因此该计算Value 间接依赖于Value This means that every time the Value changes, your entire array changes. 这意味着每次“ Value更改时,整个数组都会更改。 this will cause the foreach to re-evaluate, probably creating a fresh li for it too. 这将导致foreach进行重新评估,也可能为其创建新的li

If you return just the observable in the computed array, things work as expected: 如果仅在计算数组中返回可观察值 ,则事情将按预期工作:

 var i = 0; function CartViewModel() { var self = this; self.Value = ko.observable(i); self.centsArray = ko.computed(function() { return array = [ self.Value ]; }); } ko.bindingHandlers.slideTransition = { update: function(element, valueAccessor) { var value = valueAccessor(); var valueUnwrapped = ko.utils.unwrapObservable(value); $(element).fadeOut('slow', function() { $(element).html(valueUnwrapped); $(element).fadeIn('slow', function() { console.log('done'); }); }); } }; var vm = new CartViewModel(); ko.applyBindings(vm); setInterval(function () { vm.Value(++i); }, 1000); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script> foreach (not working): <ul data-bind="foreach: { data: centsArray}"> <li><span data-bind="slideTransition: $data"></span></li> </ul> single (working): <ul> <li><span data-bind="slideTransition: Value"></span></li> </ul> 

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

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