简体   繁体   中英

Swap 2 items in observableArray - knockout

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

Similar to Paoli's answer, but will also trigger updates to observables, could be 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);​

You can use a temporary variable:

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]

You can just use remove and splice functions directly on the observableArray like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM