希望这不是一种不好的做法,但我试图在my previous question的背景下理解Knockout可观测量。
我想用红花'更新视图。或者'蓝天',具体取决于点击的按钮。让我们假定JSON是静态的。我怎样才能使用observable来更新视图,同时只应用我的绑定一次?
https://jsfiddle.net/ft8a6jbk/3/
<button class="blue">Blue</button>
<button class="red">Red</button>
<div data-bind="text: name"></div>
<div data-bind="text: things()[0].item1"></div>
<script>
ko.applyBindings(viewModel);
</script>
var data = {
"colors": [{
"name": "blue",
"things": [{
"item1": "sky",
"item2": "ocean",
}, ]
}, {
"name": "red",
"things": [{
"item1": "flower",
"item2": "sun",
}, ]
}, ]
};
$('.blue').click(function() {
var viewModel = ko.mapping.fromJS(data.colors[0]);
});
$('.red').click(function() {
var viewModel = ko.mapping.fromJS(data.colors[1]);
});
答案 0 :(得分:2)
我只能一次只应用我的绑定吗?
像这样:
function Sample(data) {
var self = this;
self.colors = ko.observableArray();
self.currentColor = ko.observable();
ko.mapping.fromJS(data, {}, self);
}
var sample = new Sample({
"colors": [{
"name": "blue",
"things": ["sky", "ocean"]
}, {
"name": "red",
"things": ["flower", "sun"]
}]
});
ko.applyBindings(sample);
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout.mapping/2.4.1/knockout.mapping.min.js"></script>
<div data-bind="foreach: colors">
<button data-bind="text: name, click: $root.currentColor"></button>
</div>
<div data-bind="with: currentColor">
<h4 data-bind="text: name"></h4>
<div data-bind="foreach: things">
<span data-bind="text: $data" />
</div>
</div>
&#13;
注意:
click
绑定中所做的那样。这是如何工作的:
currentColor
observable。