如何结合ko.js和jQuery淡入动态绑定DOM对象?(How to combine ko.js

2019-09-21 06:30发布

我让我们说,我有以下的HTML:

<input data-bind="value: numberOne, valueUpdate: 'afterkeydown'" />
<p/>
<input data-bind="value: numberTwo, valueUpdate: 'afterkeydown'" /><p/>
<span data-bind="text: comp"></span>
<ul data-bind="foreach: stuff">
    <li><span data-bind="text: name"></span></li>
</ul>

在ko.js.以下视图模型

function myVm() {
   var self = this;
   var counter = 0;
   var myArray = new Array(5);
    for(i = 0; i < myArray.length; i++){
        myArray[i] = { name: "Blah "+( i + 1 ) };
    }
   self.stuff = ko.observableArray(myArray);
   self.numberOne = ko.observable(0);
   self.numberTwo = ko.observable(5);
   self.comp = ko.computed(function(){ 
    if(counter > 0){ 
        if(self.stuff().length > ( parseInt(self.numberOne(), 10) + parseInt(self.numberTwo(), 10) )){

            for(i = ( parseInt(self.numberOne(), 10) + parseInt(self.numberTwo(), 10) ); i < self.stuff().length; i++){
                self.stuff.pop();
            }
        }else{

                for(i = self.stuff().length; i < ( parseInt(self.numberOne(), 10) + parseInt(self.numberTwo(), 10) ); i++){
                self.stuff.push({ name: "Blah "+( i + 1 ) });
            }
        }

            }
            counter++;
            return parseInt(self.numberOne(), 10) + parseInt(self.numberTwo(), 10); 
           });
}
var vm = new myVm();
ko.applyBindings(vm);

我将如何jQuery的添加.fadeIn()函数动态添加的列表项,使他们淡出的数字改变了吗? 这里的jsfiddle链接到上面的代码: http://jsfiddle.net/HdR8L/2/

Answer 1:

一种选择是添加一个简单的fadeText结合,你可以改用的text结合。 它看起来是这样的:

ko.bindingHandlers.fadeText = {
    update: function(element, valueAccessor) {
        $(element).hide();
        ko.bindingHandlers.text.update(element, valueAccessor);
        $(element).fadeIn(1000);
    }        
};

然后,你会用它来代替现有的text样结合: http://jsfiddle.net/rniemeyer/HdR8L/3/

其他选项是使用afterAdd回调如下所述: http://knockoutjs.com/documentation/foreach-binding.html#note_5_postprocessing_or_animating_the_generated_dom_elements



文章来源: How to combine ko.js and jQuery to fade in dynamically bound DOM objects?