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

前端 未结 2 1161
粉色の甜心
粉色の甜心 2021-02-06 01:36

I have an array of articles in my Model and they are rendered nicely as HTML. What I want is to add some new articles when the user scrolls to the end of the page. I achieved th

2条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-06 01:59

    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

    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.

提交回复
热议问题