当遍历pager.Pages对象的foreach循环时,$ data是self(正如预期的那样)。但是,$ parent应该是寻呼机对象,而是返回WaterQualityResultViewModel。我做错了什么?
integer
以下模板返回:
ko.applyBindings(wqrvm, $('#dv_waterReports')[0]);
function WaterQualityResultViewModel() {
var self = this;
self.searchItem = new SearchItem();
self.items = ko.observableArray([]);
self.pager = new Pager();
self.search = function() {
$.ajax({
url: 'URL GOES HERE',
dataType: 'json',
data: {
'param': 'value'
},
async: false,
success: function(data) {
if ((data != null) && (data.searchResults !== undefined)) {
self.items(mappedItems);
self.pager.totalItemCount(data.resultsCount);
self.pager.lastPage(data.totalPages);
}
}
});
}
self.initFromUrl = function() {
var hash = getHash();
self.searchItem.geolocation(new geoLocation(0, 0, '', hash));
if (hash.currentpage !== 'undefined')
self.pager.currentPage(hash.currentpage);
if (hash.pagesize !== 'undefined')
self.pager.pageSize(hash.pagesize);
};
self.initialize = function() {
if (window.location.hash) {
self.initFromUrl();
self.search();
}
};
self.initialize();
}
function Pager() {
var self = this;
self.lastPage = ko.observable(1);
self.totalItemCount = ko.observable(0);
self.currentPage = ko.observable(1);
self.pageSize = ko.observable(10);
self.pageSlide = 2;
self.HasNextPage = ko.computed(function () {
return self.currentPage() < self.lastPage();
});
self.HasPrevPage = ko.computed(function () {
return self.currentPage() > 1;
});
self.FirstItemIndex = ko.computed(function () {
return self.pageSize() * (self.currentPage() - 1) + 1;
});
self.LastItemIndex = ko.computed(function () {
return Math.min(self.FirstItemIndex() + self.pageSize() - 1, self.totalItemCount());
});
self.Pages = ko.computed(function () {
//debugger;
var pageCount = self.lastPage();
var pageFrom = Math.max(1, self.currentPage() - self.pageSlide);
var pageTo = Math.min(pageCount, self.currentPage() + self.pageSlide);
pageFrom = Math.max(1, Math.min(pageTo - 2 * self.pageSlide, pageFrom));
pageTo = Math.min(pageCount, Math.max(pageFrom + 2 * self.pageSlide, pageTo));
var result = [];
for (var i = pageFrom; i <= pageTo; i++) {
result.push(i);
}
return result;
});
self.buildUrl = function () {
var locHash = encodeQueryData({
'currentpage': self.currentPage(),
'pagesize': self.pageSize()
});
return locHash;
};
}
答案 0 :(得分:2)
$ parent应该是寻呼机对象
基于你做出这个假设的是什么? OP中尚不清楚,因为您尚未发布完整的HTML。
因为你打过电话 applyBindings(new WaterQualityResultViewModel()); 视图模型是$ parent。
也许你认为$ parent应该引用寻呼机,因为你是数据绑定的foreach:pager.Pages。这个假设是不正确的。 Knockout知道您提供给它的DOM绑定上下文;它不知道你的Javascript对象结构。
$ parent引用viewModel本身,引用Pages数组中每个值的$ data绝对正确。