2

我想用淘汰赛替换 observableArray 中的 2 个项目,但出了点问题..

替换项目后,我将更改 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]
             );

        }

只有第一项更改为第二项,但第二项未变为第一项

4

3 回答 3

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);​
于 2012-11-27T22:32:53.303 回答
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]
于 2012-05-31T21:02:24.910 回答
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);
于 2016-02-22T23:03:09.383 回答