Using Slice With Array Created By Knockout's Mapping Plugin
-
14-11-2019 - |
Domanda
I've been struggling with this all day and I'm not sure what I'm missing. I have a working grid created using Knockout. I'm trying to convert the grid to use the mapping plugin and it breaks my paging. How do I use the slice function with the mapping plugin to return a subset of my array? What am I missing?
var grid = {};
grid.Model = function (jsondata) {
var viewModel = {
items: ko.observableArray()
};
$.getJSON('/api/test/items', function (data) {
viewModel.items= ko.mapping.fromJS(data);
ko.applyBindings(viewModel)
});
viewModel.itemsOnCurrentPage = ko.computed(function () {
return viewModel.items.slice(1, 10);
}, viewModel);
};
I'm attempting to bind to itemsOnCurrentPage (foreach: itemsonCurrentPage). Binding directly to items works fine. This worked when I was manually building my array on the client side. Now I'm grabbing the data via jQuery and using the mapping plugin. I can't figure out what I'm missing. Any help would be much appreciated.
Soluzione
RP is correct.
Here is a JSFiddle that shows what you are doing:
http://jsfiddle.net/jearles/P99zy/
Here is an update that works:
http://jsfiddle.net/jearles/P99zy/2/
The only difference is the way I load the table items.
Altri suggerimenti
Your issue is that the itemsOnCurrentPage
computed observable is bound against your original observableArray. When you do viewModel.items = ko.mapping.fromJS(data)
, you are setting viewModel.items
equal to a new observableArray (one that itemsOnCurrentPage
is not bound against).
You can instead do: ko.mapping.fromJS(data, {}, viewModel.items)
to update the existing observableArray.