What is the correct way to implement infinite scroll in knockout?

别等时光非礼了梦想. 提交于 2019-12-03 06:30:12
Salvador Dali

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. So:

1) You have to use scroll event

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.

There is also a nice MIT-license implementation here.

There is no "correct way", there are many different ways to implement infinite scroll in KnockoutJS, but I would suggest using the Knockout JS (KO) Infinite Scroll extender by thinkloop which you can find here: https://github.com/thinkloop/knockout-js-infinite-scroll

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!