3

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

When i add a new product to basket within ajax post , i call the function below with response data

renderBasket(response.data);

Example response.data like [{"name":"product 1"},{"name":"product 2"}, {"name":"product 3"}];

At first: table rows are like :

 product 1
 product 2
 product 3

AFTER i add a new product result is :

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

I've tried ko.cleanNode and basket.model.products.removeAll() before ko.applyBindings(basket.model); But i couldn't solve it.

Thank you.

4

1 回答 1

5

You should call ko.applyBindings only once (from the $(document).ready function). Just push the products on the observableArray, and you're good to go.

See http://jsfiddle.net/yCBJ8/5/ for the full example.

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);
});
于 2013-03-20T23:43:54.463 回答