使用Knockout通过点击事件从JSON更新视图

时间:2021-12-10 21:18:50

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".

每次使用Knockout触发事件(例如按钮点击)时,我都会尝试更新视图模型。单击红色按钮时,应显示“红色花朵”。单击蓝色时,应更改为“蓝天”。

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?

基本上,我只想单击一个按钮来使用适当的数据更新视图。我觉得我很亲密。我缺少什么,以及如何使用$ .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]);
});

1 个解决方案

#1


1  

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.

它可以工作,但不是推荐的使用淘汰赛的方式。

#1


1  

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.

它可以工作,但不是推荐的使用淘汰赛的方式。