如何结合ko.js和jQuery在动态绑定的DOM对象中淡入淡出? [英] How to combine ko.js and jQuery to fade in dynamically bound DOM objects?

查看:105
本文介绍了如何结合ko.js和jQuery在动态绑定的DOM对象中淡入淡出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我有以下HTML:

I let us say that I have the following 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中的以下ViewModel.

and the following ViewModel in 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/

How would I add the jQuery .fadeIn() function​ to the dynamically added list items so that they fade in as the numbers are changed? Here of the JSFiddle link to the above code: http://jsfiddle.net/HdR8L/2/

推荐答案

一个选项是添加一个简单的fadeText绑定,您可以使用它来代替text绑定.看起来像这样:

One option is to add a simple fadeText binding that you can use instead of the text binding. It would look something like:

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/

Then, you would use it in place of your existing text binding like: http://jsfiddle.net/rniemeyer/HdR8L/3/

其他选项是按此处所述使用afterAdd回调: http://knockoutjs.com/documentation/foreach-binding.html#note_5_postprocessing_or_animating_the_generation_dom_elements

The other options is to use the afterAdd callback as described here: http://knockoutjs.com/documentation/foreach-binding.html#note_5_postprocessing_or_animating_the_generated_dom_elements

这篇关于如何结合ko.js和jQuery在动态绑定的DOM对象中淡入淡出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆