我是淘汰赛的新手,并希望在页面上有两个模型的2个链接。我希望链接上的click事件切换显示哪个视图模型。我已经尝试了几种方法并且有一个jfiddle https://jsfiddle.net/edgrttj3/7/,但我无法让它发挥作用。关于我可能做错什么的任何想法?
<div id="content">
<a id="button1" href="#" >View 1</a>
<a id="button2" href="#" >View 2</a>
<hr />
<div data-bind="with: selectedView">
<div data-bind="template: { name: templateName, data: data }"></div>
</div>
<script id="oneTmpl" type="text/html">
<ul data-bind="foreach: items">
<li>
<span data-bind="text: id"></span>
<input data-bind="value: name" />
</li>
</ul>
</script>
<script id="twoTmpl" type="text/html">
First:
<input data-bind="value: firstName" />
Last:
<input data-bind="value: lastName" />
</script>
</div>
这是javascript:
var View = function (title, templateName, data) {
this.title = title;
this.templateName = templateName;
this.data = data;
};
var subModelA = {
items: ko.observableArray([
{ id: 1, name: "one" },
{ id: 2, name: "two" },
{ id: 3, name: "three" }
])
};
var subModelB = {
firstName: ko.observable("Bob"),
lastName: ko.observable("Smith")
};
var viewModel = {
views: ko.observableArray([
new View("one", "oneTmpl", subModelA),
new View("two", "twoTmpl", subModelB)
]),
selectedView: ko.observable()
};
function setSelectedView(newview) {
alert(newview);
if (newview == "oneTmpl") {
viewModel.selectedView = viewModel.views[0];
} else {
viewModel.selectedView = viewModel.views[1];
}
};
ko.applyBindings(viewModel);
document.getElementById ("button1").addEventListener("click", setSelectedView('oneTmpl'), false);
document.getElementById ("button1").addEventListener("click", setSelectedView('twoTmpl'), false);
答案 0 :(得分:2)
实际上你的实施几乎就在那里。你需要做几件调整。
selectedView(valueIsHere)
传递。views()[0]
以下是更新后的实现方式:
var View = function (title, templateName, data) {
this.title = title;
this.templateName = templateName;
this.data = data;
};
var subModelA = {
items: ko.observableArray([
{ id: 1, name: "one" },
{ id: 2, name: "two" },
{ id: 3, name: "three" }
])
};
var subModelB = {
firstName: ko.observable("Bob"),
lastName: ko.observable("Smith")
};
var ViewModel = function (){
this.views = ko.observableArray([
new View("one", "oneTmpl", subModelA),
new View("two", "twoTmpl", subModelB)
]);
this.selectedView = ko.observable();
this.select = function(id){
if (id === 1) {
this.selectedView(this.views()[0]);
} else {
this.selectedView(this.views()[1]);
}
};
};
ko.applyBindings(new ViewModel());
以下是按钮的一些更改:
<a id="button1" href="#" data-bind="click: select(1)">View 1</a>
<a id="button2" href="#" data-bind="click: select(2)">View 2</a>