如何使用自定义绑定为Knockout.js中使用“foreach”添加的元素设置动画

时间:2016-07-13 16:18:16

标签: javascript jquery knockout.js jquery-animate

我想要使用knockout.js“foreach”函数添加到页面中的图像数组如下:

ListModel
{
    id:listModel
}
TableView
{
    id: tableView
    selectionMode:SelectionMode.SingleSelection 
    model: listModel
    TableViewColumn
    {
        role: "myRole"
        title: "myTitle"
    }
    onRowCountChanged:
    {
        if (rowCount > 0) 
        {
            var defaultEntityIndex = 0;
            for (var i = 0; i < rowCount; i++)
            {
                if (model.get(i).role == qsTr("NameOfTheDefaultItem"))
                    defaultEntityIndex = i;
            }
            // select the default item and also set it as current so that it is highlighted
            currentRow = defaultEntityIndex
            selection.select(defaultEntityIndex)
            // move the view to the item so that the user knows that something got selected without his input....though this function actually does not seem to be working
            positionViewAtRow(defaultEntityIndex, ListView.Beginning)
            focus = true     
        }
    }
    Connections
    {
        target: tableView.selection
        onSelectionChanged : 
        {
            if (tableView.currentRow >= 0)
                myC++Class.selectedThing = listModel.get(tableView.currentRow).role;
         }
    }
}
function initList()
{
    var vals = myC++Class.getTheListWithData();
    for(var i =0; i<vals.length; i++)
    {
        listModel.append({role: vals[i]});
    }
    // the lines that were here in the original post are (as expected) not needed
}
Component.onCompleted:
{
    initList();
}
Connections // this is to re-fresh the tableView when my data changes
{
    target: myC++class
    onDataChanged: initList();
}

我的自定义绑定是:

<div class="animation" data-bind="foreach: { data: frames }">
    <img data-bind="fadeInVisible: true" src="./media/test.jpg" />
</div>

我的问题是他们都在同一时间进来,我希望他们交错进来。有没有一种很好的方法来交错他们我可以使用淘汰赛?

我想我可以使用jQuery队列在我调用自定义绑定时向队列中添加动画,然后在最后我可以运行动画队列,但我不知道该怎么做。< / p>

谢谢。

1 个答案:

答案 0 :(得分:1)

将延迟乘以foreach循环中项的索引。项目零将为0 * 1000ms,项目1将具有1 * 1000ms的延迟等。

<强> HTML:

<div class="animation" data-bind="foreach: { data: frames }">
    <img data-bind="fadeInVisible: true" src="./media/test.jpg" />
</div>

<强>使用Javascript:

ko.bindingHandlers.fadeInVisible = {
    init: function (element, valueAccessor) {
        var index = $index();
        $(element).hide().delay(index * 1000).fadeIn();
    }
};