What is the correct way to implement infinite scrolling in a knockout?

I have an array of articles in my model and they render perfectly as HTML. I want to add new articles when the user scrolls to the bottom of the page. I achieved this, but, in my opinion, with some really hacky behavior: everything I did was added by the jQuery $(window).scroll , for example:

 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 well, but I think this scroll will be called even if I hide my model.

So, is there a more suitable way to do the same behavior?

+8
javascript infinite-scroll
source share
2 answers

Since no one answered my question, but Jerouen gave me a hint what to look at, I will try to answer my question with what I found. So:

1) You must use the 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); 

It was taken from here and similar approaches with scrollOptions here .

There is also an implementation of the MIT license .

+15
source share

There is no β€œright way”, there are many different ways to implement endless scrolling in KnockoutJS, but I would suggest using thinkloop's Infinite Scroll Knockout JS (KO) extender, which you can find here: https://github.com/thinkloop/knockout- js-infinite-scroll

+1
source share

All Articles