How to combine ko.js and jQuery to fade in dynamically bound DOM objects?

怎甘沉沦 提交于 2019-12-23 03:51:44

问题


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>

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);

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/


回答1:


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);
    }        
};

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

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



来源:https://stackoverflow.com/questions/11979695/how-to-combine-ko-js-and-jquery-to-fade-in-dynamically-bound-dom-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!