Reputation: 16086
I'm learning Knockout and trying something as below. Data gets displayed, but what I want is data to be bound in chunks. For example the first 3 will get bound, then the next 3, then next 3, etc.
In other words: How can I push "people" in the observable array in "chunks".
Below is some sample code. In my actual case I'm binding images, and they are taking time to load, so that is why I want to bind data in chunks.
Here is my viewModel:
var viewModel = {
topicsList : ko.observableArray()
};
Here is the data binding:
dispatcher(viewEvent, function(event, data){
$.each(data, function(){
viewModel.people.push(this);
});
});
ko.applyBindings(new viewModel);
Here is my HTML:
<div data-bind="foreach: people">
<div data-bind="text:firstName"></div
</div>
For pushing people in observable array I tried something like this:
dispatcher(viewEvent, function(event, data) {
var loop = 0;
$.each(data, function(){
++loop;
viewModel.topicsList.push(this);
if(loop%3==0) {
ko.applyBindings(viewModel);
});
});
Upvotes: 0
Views: 202
Reputation: 63729
You could rewrite your view models a bit so that the src
for images would be computed: a placeholder image as a basis, or the actual image URL when it is time for the image to be loaded. Like this:
function personViewModel(url) {
var self = this;
self.firstName = ko.observable("Johndoe");
self.imageUrl = ko.observable(url);
self.mayLoad = ko.observable(false);
self.imageSrc = ko.computed(function() {
return self.mayLoad() ? self.imageUrl() : "http://soulclimbing.mobi/Content/Media/image-loading-animation.gif";
});
}
Something like this view could be used:
<div data-bind="foreach: people">
<div>
<span data-bind="text:firstName"></span>
<br />
<img data-bind="attr: {src: imageSrc}" />
</div>
</div>
For loading images in chunks of three, there are various options. A baseline, hackish, naive solution, with just starting a new chunk every X seconds using setInterval. Something like this jsfiddle.
Better would be to use the event binding to start download of a next image, when one is loaded. However, checking if images are loaded is very hard (caching and whatnot), so you may want to use a library to handle things. See, for example this answer.
Upvotes: 1