Search code examples
javascriptknockout.jsknockout-mapping-pluginobservable

How to update a view on a model change using knockout.js?


How do you update the view to a change what happens in the viewmodel code?

The app below displays a list of entries and updates the totals. It works and I can get the updated data out and into a JSON object and can update a model variable with the modified data when I click a button.

console.log(ko.toJSON(self.List()));  

The view does not update on button click

<span data-bind="text: jsonList"></span>

What do I have to do to update the view? I have tried variations of the following:

self.jsonList=ko.observable(ko.toJSON(self.List()))
self.show = function(){//the button click function
    self.jsonList = ko.computed(function(){
        var newval = self.jsonList()
        newval = ko.toJSON(self.List())
        console.log(jsonList())
        //newval.valueHasMutated();
        return newval;
    })
}

Here is the fiddle


Solution

  • your code was not correctly updating the observable below is a modified version of your code that update the JSON string on click, as well as an implementation of it via a computed observable (jsonList2)

    the forked fiddle can be found at http://jsfiddle.net/n0jfhs8k/2/

    self.show = function(){//the button click function
        self.jsonList(ko.toJSON(self.List()));
    }
    
    self.jsonList2 = ko.computed(function(){
            var newval = self.jsonList()
            newval = ko.toJSON(self.List())
            return newval;
        });