在observableArray中交换2个项目 - 淘汰赛

时间:2012-05-31 16:10:12

标签: javascript knockout.js observablecollection knockout-2.0

试图在observableArray中使用淘汰赛中的两个项目之间进行替换,但是出了点问题......

更换项目后,我将更改并将displayOrder属性(在两个itmems中)发送到服务器(或者我应该采取其他方法)

        ReplaceBetweenTwoitemsInArray: function () {
            console.log("ranking down msg");
            var currentItemindex = viewModel.myobservableArray.indexOf(this); 
            var nextItemIndex = currentItemindex + 1;
            viewModel.myobservableArray .replace(
                 viewModel.myobservableArray ()[nextItemIndex], 
                viewModel.myobservableArray ()[currentItemindex]
             );

        }

只有第一项改为第二项,但第二项不成为第一项

3 个答案:

答案 0 :(得分:3)

与Paoli的答案类似,但也会引发对可观察者的更新,可能是DRYer。

http://jsfiddle.net/marrok/ckMJE/101/

<ul data-bind="foreach: colors">
    <li><span data-bind="text:color"></span>
    </li>
</ul>
<br/>
<span>From:</span><input type="text" data-bind="value:from"/>
<br/>
<span>TO:</span><input type="text" data-bind="value:to"/>
<br/>
<button data-bind="click:swap">Swap It</button>​

使用Javascript:

var ViewModel = function() {
    this.self = this;
    self.from = ko.observable(0); // default
    self.to = ko.observable(1); // default
    self.colors = ko.observableArray([{
        color: 'red'},
    {
        color: 'green'},
    {
        color: 'pink'},
    {
        color: 'blue'},
    {
        color: 'yellow'}]);

    self.swap= function() {
        var iTo = parseInt(self.to());
        var iFrom = parseInt(self.from());
        var from = self.colors()[iFrom];
        var to = self.colors()[iTo];
        console.log("Before", self.colors().map(function(d){return d.color;} ), from, to, iFrom, iTo)
        self.colors()[iTo] = from;
        self.colors()[iFrom] = to;
        console.log("After ", self.colors().map(function(d){return d.color;} ), from, to, iFrom, iTo)
        self.colors.valueHasMutated()

    };
};
model = new ViewModel()
ko.applyBindings(model);​

答案 1 :(得分:2)

您可以使用临时变量:

var arr = ko.observableArray([0, 1])

// Should produce arr() = [0, 1]

var tmp = arr()[0];

arr()[0] = arr()[1];
arr()[1] = tmp;

// At this point, arr() is [1, 0]

答案 2 :(得分:0)

您可以直接在observableArray上使用remove和splice函数,如下所示:

var arr=ko.observableArray(["x","y"]);
var index=arr.indexOf("y");
var tmp=arr()[index-1];
arr.remove(tmp);
arr.splice(index,0,tmp);