Question

I have following knockout.js mapping code:

    //JSON string
    var startData= {"Name":"SMT","Price":{"Value":22,"Currency":"EUR"}}";

    //convert json to model
    var viewModel = ko.viewmodel.fromModel(startData);

    viewModel.deletePrice= function() {
        delete this.Price;
    };

  ko.applyBindings(viewModel);

Then, I have following template that shows Price nested object on the page:

<script type="text/html" id="PriceTemplate">
//render Value and Currency properties from nested object Price
</script>

Then in my code, I bind Price object to the teplate PriceTemplate - and this all works OK.

<div data-bind="template: { name: 'PriceTemplate', data: Price, templateOptions: { title: 'Prc'} }"></div>

    <a href="#" data-bind="click: function() { deletePrice() }">Delete Price</a>

The problem is this function deletePrice(). When it is called, it deletes the nested object Price, but the template is still rendered on the page with the initial data.

My question - how can I delete Price nested object and at same time remove rendered template?

Was it helpful?

Solution

I just found a solution (using ViewModel knockout extension):

var viewModel = ko.viewmodel.fromModel(startData,{
    extend:{
        "{root}.Price":function(obj){
     return typeof(obj) == "object" ? ko.observable(obj) : ko.observable(null);    
                        }
    }
});

viewModel.deletePrice = function() {
    this.Price(null);
};

OTHER TIPS

You're deleting the property from the object which is not an observable event. Is there any reason you can't set the value of price as an observable this.Price(null)? This would trigger the observable change necessary to update the UI.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top