[英]What is the correct way to implement infinite scroll in knockout?
I have an array of articles in my Model and they are rendered nicely as HTML. 我的模型中有一系列文章,它们很好地呈现为HTML。 What I want is to add some new articles when the user scrolls to the end of the page. 我想要的是在用户滚动到页面末尾时添加一些新文章。 I achieved this, but in my opinion with some really hacky behavior: all I have done is added jquery event handler $(window).scroll
, like this: 我实现了这一点,但在我看来有一些非常hacky行为:我所做的就是添加jquery事件处理程序$(window).scroll
,如下所示:
function ArticlesViewModel() {
var self = this;
this.listOfReports = ko.observableArray([]);
this.loadReports = function() {
$.get('/router.php', {type: 'getReports'}, function(data){
self.listOfReports(self.listOfReports().concat(data));
}, 'json');
};
this.loadReports();
$(window).scroll(function() {
if($(window).scrollTop() == $(document).height() - $(window).height()) {
self.loadReports();
}
})
};
In my simple prototype scenario it works nicely, but I think that this scroll will be called even if I will hide my model. 在我简单的原型场景中它很好用,但我认为即使我隐藏我的模型也会调用此滚动。
So is there a more appropriate way to do the same behavior? 那么有更合适的方法来做同样的行为吗?
Because no one has answered my question, but Jeroen gave me a hint where to look at, I will attempt to answer my question with what I have found. 因为没有人回答我的问题,但是Jeroen给了我一个暗示在哪里看,我将尝试用我发现的东西回答我的问题。 So: 所以:
1) You have to use scroll event 1)你必须使用滚动事件
View 视图
<div id="main" data-bind="foreach: items, event: { scroll: scrolled }">
<div data-bind="text: name"></div>
</div>
ViewModel 视图模型
var viewModel = {
items: ko.observableArray([]),
scrolled: function(data, event) {
var elem = event.target;
if (elem.scrollTop > (elem.scrollHeight - elem.offsetHeight - 200)) {
getItems(20);
}
},
maxId: 0,
pendingRequest: ko.observable(false)
};
function getItems(cnt) {
if (!viewModel.pendingRequest()) {
var entries = [];
for (var i = 0; i < cnt; i++) {
var id = viewModel.maxId++;
entries.push({
id: id,
name: "Name" + id
});
}
viewModel.pendingRequest(true);
$.ajax({
type: 'POST',
url: '/echo/json/',
data: {json: ko.toJSON(entries), delay: .1},
success: function(entries) {
ko.utils.arrayForEach(entries, function(entry) {
viewModel.items.push(entry);
});
viewModel.pendingRequest(false);
},
error: function() {
viewModel.pendingRequest(false);
},
dataType: 'json'
});
}
}
ko.applyBindings(viewModel);
getItems(20);
Was taken from here and similar approaches with scrollOptions here . 这里采用的是scrollOptions类似的方法。
There is also a nice MIT-license implementation here . 这里还有一个很好的MIT许可证实现 。
没有“正确的方法”,在KnockoutJS中有很多不同的方法来实现无限滚动,但我建议使用thinkloop的Knockout JS(KO)无限滚动扩展器,你可以在这里找到: https : //github.com/ thinkloop /敲除-JS-无限滚动
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.