daveycroqet daveycroqet - 3 months ago 17
Javascript Question

Using Knockout to update the view from JSON via click event

I'm attempting to update the view model every time an event fires (e.g. button click) using Knockout. When the red button is clicked, it should read "red flower". When blue is clicked, this should change to "blue sky".

Basically, I just want clicking a button to update the view with the appropriate data. I feel like I'm close. What am I missing, and how would I extend this logic with a

$.getJSON
?

Fiddle:



https://jsfiddle.net/ft8a6jbk/3

HTML:



<button class="red">Red</button>
<button class="blue">Blue</button>

<div data-bind="text: name"></div>
<div data-bind="text: things()[0].item1"></div>

<script>
ko.applyBindings(viewModel);
</script>


JS:



var data = {
"colors": [{
"name": "blue",
"things": [{
"item1": "sky",
"item2": "ocean",
}, ]
}, {
"name": "red",
"things": [{
"item1": "flower",
"item2": "sun",
}, ]
}, ]
};

$('.red').click(function() {
var viewModel = ko.mapping.fromJS(data.colors[0]);
});

$('.blue').click(function() {
var viewModel = ko.mapping.fromJS(data.colors[1]);
});

Answer

You can try that:

$('.red').click(function() {
  var viewModel = ko.mapping.fromJS(data.colors[0]);
  ko.cleanNode(document);
  ko.applyBindings(viewModel);
});

$('.blue').click(function() {
  var viewModel = ko.mapping.fromJS(data.colors[1]);
  ko.cleanNode(document);
  ko.applyBindings(viewModel);
});

It works but it's not the recommended way to use knockout.