How do I swap two items in an observableArray?

后端 未结 4 1865
轮回少年
轮回少年 2020-12-03 05:05

I have a button that moves an item one position left in an observableArray. I am doing it the following way. However, the drawback is that categories()[index] gets removed f

4条回答
  •  自闭症患者
    2020-12-03 05:34

    I know this answer comes a bit late, but I thought it might be useful to others who want a more general swap solution. You can add a swap function to your observableArrays like so:

    ko.observableArray.fn.swap = function(index1, index2) {
        this.valueWillMutate();
    
        var temp = this()[index1];
        this()[index1] = this()[index2];
        this()[index2] = temp;
    
        this.valueHasMutated();
    }
    

    You can then use this function to swap two elements in an array given their indices:

    myArray.swap(index1, index2);
    

    For a moveUp function, you could then do something like this:

    moveUp: function(category) {
        var i = categories.indexOf(category);
        if (i > 0) {
            categories.swap(i, i+1);
        }
    }
    

提交回复
热议问题