Knockout.js applyBindings两次重复结果

时间:2013-03-20 23:01:22

标签: knockout.js

HTML

<table cellpadding="0" cellspacing="0" border="0">
<thead>
    <tr><th width="483"><span>Product Name</span></th></tr>
</thead>
<tbody data-bind='foreach: basket.model.products()'>
    <tr><td><div class="ml10 productDetails" data-bind="text: name"></div></td></tr>            
</tbody>
</table>    

JAVASCRIPT CODE

var ProductLine = function(data) {
    var self = this;
    self.name         = ko.observable(data.name);

};

function BasketModel(data) {
    var self                = this;                     
    self.initialData        = ko.observable(data);      
    self.products           = ko.observableArray();

    $.each(self.initialData().products,function(i,val){
        self.products.push(new ProductLine(this));
    });
}
function renderBasket(data){        

    basket = { model: new BasketModel(data)};
    ko.applyBindings(basket.model);
}   
$(document).ready(function(){
    var sampleData = [{"name":"product 1"},{"name":"product 2"}];
    renderBasket(sampleData );
});

当我在ajax帖子中将新产品添加到购物篮时,我使用响应数据

调用下面的函数
renderBasket(response.data);

示例response.data之类的      [{“name”:“product 1”},{“name”:“product 2”},{“name”:“product 3”}];

起初: 表行如:

 product 1
 product 2
 product 3

我添加新产品后 结果是:

product 1
product 1
product 1
product 2
product 2
product 2
product 3
product 3
product 3

我在ko.applyBindings(basket.model)之前尝试了ko.cleanNode和basket.model.products.removeAll(); 但我无法解决它。

谢谢。

1 个答案:

答案 0 :(得分:5)

您应该只调用ko.applyBindings一次(来自$(document).ready功能)。只需将产品推到observableArray上,就可以了。

有关完整示例,请参阅http://jsfiddle.net/yCBJ8/5/

var ProductLine = function (data) {
        var self = this;
        self.name = ko.observable(data.name);
    },
    BasketModel = function (data) {
        var self = this;

        self.products = ko.observableArray();

        self.addToBasket = function (d) {
            $.each(d, function (i, v) {
                self.products.push(new ProductLine(this));
            });
        };

        self.replaceBasket = function (d) {
            self.products.removeAll();
            self.addToBasket(d);
        };

        self.addToBasket(data);
    };

$(document).ready(function () {
    var initialData = [{"name": "product 1"}, {"name": "product 2"}],
        basket = {
            model: new BasketModel(initialData)
        };

    ko.applyBindings(basket.model);
});