Reputation: 21
I'm using knockoutjs to bind data and this is the first time I use knockoutjs, I have a list data show to table, when user scroll down to bottom, it's will be load more new data. Here is my code:
HTML:
<div data-bind="template: { name: 'product-template', foreach: listProduct }" id="data-list"></div>
<script type="text/html" id="product-template">
<table>
<tr>
<td data-bind="text:name"></td>
<td data-bind="text:description"></td>
</tr>
</table>
</script>
and JS here:
var product = {
get : function(pageNumber){
var self = this;
self.listProduct = ko.observableArray([]);
request.product(pageNumber, function(resp){
//response list data of product
//example: {"data":[{"name":"sony","desciption":"this is sony"},{"name": "toshiba","description": "this is toshiba"}]};
if(pageNumber>1){
self.listProduct.push(resp.data);
}else{
self.listProduct(resp.data);
}
})
}
}
and then I call function like this:
ko.applyBindings(new product.get(1), document.getElementById("data-list"));// it's success to bind data
and bind more data when I call scroll down to bottom event:
ko.applyBindings(new product.get(2), document.getElementById("data-list"));// I got error: Error You cannot apply bindings multiple times to the same element
There is any something wrong? thanks.
Upvotes: 1
Views: 36
Reputation: 4222
I think what you want to do is something like infinite scroll, so see the example, i think this will simplify what you doing.
var viewModel = {
items: ko.observableArray([]),
//this function always will be called when scroll event was trigered
scrolled: function(data, event) {
var elem = event.target;
if (elem.scrollTop > (elem.scrollHeight - elem.offsetHeight - 200)) {
getItems(20);
}
},
//you can use this like your page
maxId: 0
};
function getItems(cnt) {
//here you do the requst for the data
//create fake data to pass to echo service
for (var i = 0; i < cnt; i++) {
var id = viewModel.maxId++;
viewModel.items.push({
id: id,
name: "Name" + id
});
}
}
ko.applyBindings(viewModel);
getItems(20);
#main { height: 500px; width: 500px; overflow: scroll; }
#main div { background-color: #eee; margin: 5px; height: 100px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<div>
<span data-bind="text: items().length"></span>
</div>
<div id="main" data-bind="foreach: items, event: { scroll: scrolled }">
<div data-bind="text: name"></div>
</div>
Upvotes: 1