2

im tring to Replace between 2 items in observableArray with knockout but something is wrong..

after the replace of the items ,i will change and send the displayOrder property (in both itmems) to the server (or should i take other approach for this)

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

        }

only the first item changed to the second item but the second item doesnt become the first one

4

3 に答える 3

3

Paoli's answer に似ていますが、オブザーバブルの更新もトリガーし、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 に答える