Knockout Sortable with two lists and one filtered

2019-08-22 13:53发布

问题:

I'm attempting to use the knockout sortable plugin to work with two html lists based off of one knockout array filtered into two arrays. I keep getting errors and I believe it may have to do with the fact that I'm returning "computed" instead of "observableArray" objects, but I haven't been able to find a solution.

http://jsfiddle.net/thebassix/Eg2DG/4/

I believe my main part of the problem is:

hiddenSeries = ko.computed(function() {
    {
        var seriesArray = self.series();
        return ko.utils.arrayFilter(seriesArray, function(item) {
            return item.Hidden();
        });
    }
});

unhiddenSeries = ko.computed(function() {
    {
        var seriesArray = self.series();
        return ko.utils.arrayFilter(seriesArray, function(item) {
            return !(item.Hidden());
        });
    }
});

回答1:

The sortable plugin needs an observableArray to operate on, so that it can place the item back into the correct location.

Your best bet is probably to split the data into two observableArrays and then create a computed to represent the combined set (if you need to send it back to the server).

Maybe something along the lines of:

var data = ko.mapping.fromJSON('[{"__type":"mediacenter+Series","ID":1,"Name":"seriesname232","Hidden":true,"MediaCenterID":1,"_destroy":false},{"__type":"mediacenter+Series","ID":2,"Name":"kjhkuhkuh","Hidden":false,"MediaCenterID":1,"_destroy":false},{"__type":"mediacenter+Series","ID":3,"Name":"trrde","Hidden":false,"MediaCenterID":1,"_destroy":false},{"__type":"mediacenter+Series","ID":4,"Name":"1","Hidden":true,"MediaCenterID":1,"_destroy":false}]', mappingOptions);

//take one pass through the records and put them in the appropriate bucket
var hidden = [], 
    unhidden = [];

ko.utils.arrayForEach(data(), function(item) {
    if (item.Hidden()) {
       hidden.push(item);   
    }
    else {
       unhidden.push(item);   
    }
});

self.hiddenSeries = ko.observableArray(hidden);
self.unhiddenSeries = ko.observableArray(unhidden);

//define series as the two lists together
self.series = ko.computed(function() {
   return self.hiddenSeries().concat(self.unhiddenSeries()); 
});

Sample: http://jsfiddle.net/rniemeyer/NhUEm/