无法将新数据推送到knockoutjs?

时间:2015-12-26 02:25:24

标签: javascript jquery knockout.js

我正在使用knockoutjs绑定数据,这是我第一次使用knockoutjs,我有一个列表数据显示到表,当用户向下滚动到底部时,它将加载更多的新数据。这是我的代码:

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>

和JS在这里:

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);
            }
        })
    }
}

然后我调用这样的函数:

ko.applyBindings(new product.get(1), document.getElementById("data-list"));// it's success to bind data
当我调用向下滚动到底部事件时

并绑定更多数据:

ko.applyBindings(new product.get(2), document.getElementById("data-list"));// I got error: Error You cannot apply bindings multiple times to the same element

有什么不对吗?感谢。

1 个答案:

答案 0 :(得分:1)

我认为你想要做的就是无限滚动,所以看看这个例子,我想这会简化你的工作。

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>