我正在开发一个Asp.Net MVC应用程序,我在其中使用OData和Knockout JS View模型将数据呈现到表格中的网页上。 现在我只想在页面上呈现我的可观察数组的前三个元素。 我尝试使用Knockout Js的拼接功能,但似乎无法正常工作。
我有以下代码。
Knockout Js View Model
var CanadianCrudeViewModel = function () {
var self = this;
self.canadiancrudes = ko.observableArray();
$.ajax({
dataType: "json",
url: '/odata/Canadiancrudes',
data: ko.toJSON(self.products),
async: false,
success: function (data) {
self.datainput((ko.utils.arrayMap(data.value, function (canadiancrude) {
var obsCanadianCrude = {
Id: canadiancrude.Id,
Term: ko.observable(canadiancrude.Term),
Product: canadiancrude.Product,
Location: ko.observable(canadiancrude.Location),
Pipeline: ko.observable(canadiancrude.Pipeline),
BidCP: ko.observable(canadiancrude.BidCP),
BidVolume: ko.observable(canadiancrude.BidVolume),
Index: ko.observable(canadiancrude.Index),
Bid: ko.observable(canadiancrude.Bid),
Offer: ko.observable(canadiancrude.Offer),
OfferVolume: ko.observable(canadiancrude.OfferVolume),
OfferCP: ko.observable(canadiancrude.OfferCP),
Locked: ko.observable(canadiancrude.Locked),
Sequence: ko.observable(canadiancrude.Sequence),
TermID: ko.observable(canadiancrude.TermID),
Edit: ko.observable(false)
}
//self.datainput.splice(0, 1);
self.watchModel(obsCanadianCrude, self.modelChanged);
return obsCanadianCrude;
})));
}
});
$.getJSON('/odata/Canadiancrudes', function (data) {
self.canadiancrudes(ko.utils.arrayMap(data.value, function (canadiancrude) {
var obsCanadianCrude = {
Id: canadiancrude.Id,
Term: ko.observable(canadiancrude.Term),
Product: canadiancrude.Product,
Location: ko.observable(canadiancrude.Location),
Pipeline: ko.observable(canadiancrude.Pipeline),
BidCP: ko.observable(canadiancrude.BidCP),
BidVolume: ko.observable(canadiancrude.BidVolume),
Index: ko.observable(canadiancrude.Index),
Bid: ko.observable(canadiancrude.Bid),
Offer: ko.observable(canadiancrude.Offer),
OfferVolume: ko.observable(canadiancrude.OfferVolume),
OfferCP: ko.observable(canadiancrude.OfferCP),
Locked: ko.observable(canadiancrude.Locked),
Sequence: ko.observable(canadiancrude.Sequence),
TermID: ko.observable(canadiancrude.TermID),
Edit: ko.observable(false),
selectedOptionValue: ko.observable(canadiancrude.Product)
}
// self.canadiancrudes.splice(1, 3);
self.watchModel(obsCanadianCrude, self.modelChanged);
return obsCanadianCrude;
}))
});
};
$(function () {
viewModel.canadiancrudes.splice(0, 2);
viewModel.canadiancrudes.push(obsCanadianCrude);
ko.applyBindings(viewModel);
});
我不确定我是以正确的方式做到这一点,还有其他更好的方法我至少可以使用计算功能吗?
答案 0 :(得分:0)
像...这样的东西。
(是的,我确定此代码可以优化)
vm.firstThree = ko.computed(function() {
var ret = vm.canadiancrudes();
// Cheap clone
ret = ko.mapping.fromJS(ko.mapping.toJS(ret))
// Not sure if you'll need bounds checking here or not.
ret = ret.slice(0, 2);
return ret;
});