Önay Yalcıner
Önay Yalcıner

Reputation: 3

knockoutjs refresh or update

I trying create a ajax-refresh shopping-cart panel. My shopping-cart is listed but I can't refresh it in $.getJSON callback function. my view and code is;

<div class="panel panel-info">
    <div class="panel-heading">
        <i class="fa fa-list-ul"></i> Sipariş Listeniz
    </div>
    <div class="panel-body">
        <div id="cart" data-bind="foreach: Currencies">
            <div class="">
                <span data-bind="text: Currency"></span>
                <table class=" table table-striped" data-bind="foreach: Items">
                    <tr>
                        <td data-bind="text: Code"></td>
                        <td data-bind="text: Amount"></td>
                        <td data-bind="text: Price"></td>
                        <td data-bind="text: LineTotal"></td>
                    </tr>
                </table>
            </div>
        </div>
    </div>
    <div class="panel-footer">
    </div>
</div>

and

var cartViewModel = {
    Currencies: ko.observableArray()
};

$(function () {
    ShowCart();
});

function AddToCart(i, a) {
    $.getJSON('@Url.Action("AddToCart", "Products")/' + i + '?Amount=' + a, null, function (d) {
        if (d)
            ShowCart();
    });
}
function ShowCart() {
    $.getJSON('@Url.Action("GetCart","Products")', null, function (c) {
        cartViewModel.Currencies = ko.observableArray(c);
        cartViewModel.Currencies.valueHasMutated();
        ko.applyBindings(cartViewModel);
    });
}

How can I refresh the binding in the $.getJSON callback?

Upvotes: 0

Views: 61

Answers (1)

awj
awj

Reputation: 7949

I think your problem is that you're overwriting the observables in your view-model.

All you need to do is pass a new value into the existing observable.

Try this instead:

function ShowCart() {
    $.getJSON('@Url.Action("GetCart","Products")', null, function (c) {
        cartViewModel.Currencies(c);
    });
}

Upvotes: 3

Related Questions