在observableArray
问题描述:
单个对象的双向绑定
我的页面如下:在observableArray
<button id="add">Add Data</button>
<button id="show">show</button>
<table>
<tr style="vertical-align:top">
<td>
<table border="1">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
</tr>
</thead>
<tbody data-bind="foreach: students">
<tr>
<td data-bind="text: id"></td>
<td>
<input type="text" data-bind="value: name" />
</td>
<td> <a href="javascript:void(0)" data-bind="click: $root.showData">Select</a>
</td>
</tr>
</tbody>
</table>
</td>
<td>
<table id="data">
<tbody data-bind="with: selectedData">
<tr>
<td>Id</td>
<td>
<input type="text" data-bind="value: id" />
</td>
</tr>
<tr>
<td>Name</td>
<td>
<input type="text" data-bind="value: name" />
</td>
</tr>
<tr>
<td></td>
<td>
<input type="button" value="Close" />
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</table>
的JavaScript如下:
function ViewModel() {
var self = this;
self.students = ko.observableArray([]);
self.showData = function (dt) {
if (window.console) console.log(dt);
self.selectedData(dt);
$('#data').show();
}
this.selectedData = ko.observable();
}
$(function() {
window.appViewModel = new ViewModel();
ko.applyBindings(window.appViewModel);
$('#add').click(function() {
var model = window.appViewModel;
$.each(students, function (idx, student) {
if (window.console) console.log(student);
model.students.push(student);
});
$('table').show();
});
$('table').hide();
$('input').click(function() {
$('#data').hide();
});
$('#show').click(function() {
var s = JSON.stringify(window.appViewModel.students());
alert(s);
});
});
前瞻:
在图片中,我点击与id = 3的学生相对应的选择。另一张表显示为t他选择了学生的细节。假设我在文本框1中输入了一些内容,文本框2不更新,反之亦然。
如何做到这一点?
答
你的输入没有更新,因为id
和name
值不被存储或结合针对observables
,这是特殊的对象,敲除专门为此目的提供。您可以通过添加一个新的Student
类型与您的代码很容易地解决这个问题:
function Student(data) {
this.id = ko.observable(data.id);
this.name = ko.observable(data.name);
};
,并用它来与来填充你的students
阵列:
$.each(students, function (idx, student) {
if (window.console) console.log(student);
model.students.push(new Student(student));
});
有了这些属性现在被observables
,其变动将传播到用户界面。这是the fiddle,这两个小改动。
这就是说,我认为你很大程度上错过了淘汰赛的重点。我强烈建议你通过Knockout tutorials,如果你还没有这样做。
您使用jQuery为您的viewmodel创建click
函数确实违背了Knockout鼓励的模型。请查看this fiddle,它使用viewmodel函数将代码转换为100%Knockout,并删除所有jQuery。