4
我是新來淘汰賽,並希望有2個模型的網頁上的2個鏈接。我希望鏈接上的點擊事件切換顯示哪個視圖模型。我已經嘗試了幾種方法,並且有一個快捷方式https://jsfiddle.net/edgrttj3/7/但我無法使其工作。任何想法,我可能做錯了什麼?Knockout綁定2鏈接到不同的意見和swich modelview
<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);
自舉聽起來不錯,但最終我還是想在這裏展開,並放置在不同的HTML文件的意見,瞭解如何能夠在更大的視圖集上進行淘汰,並通過鏈接更改顯示的視圖,並使用挖空裝訂設置模型數據。 – KH1229
@ KH1229我改變了解決方案:) – muhihsan
這很好!謝謝 – KH1229