【发布时间】:2015-08-27 08:26:11
【问题描述】:
我有一个复选框,它绑定到我的 observableArray 中使用的对象的属性。单击时,我无法正确更新复选框。当我单击它时,该值没有正确设置,复选框也没有取消选中。示例绑定直接在 ViewModel 上具有属性,而不是在 ViewModel 内部使用的对象的属性。任何人都可以阐明如何使其正常工作吗?
<tbody id="StatusGrid" data-bind="foreach:{data: Statuses, as: 'status'}">
<tr data-bind="attr: { index: $index }" style="padding-bottom:5px;">
<td style="padding-bottom:5px;">
<input class="statusID" data-bind="value: status.StatusID, visible: status.ShowID, attr: { name: 'Statuses[' + $index() + '].StatusID'}" />
</td>
<td style="padding-bottom:5px;">
<input class="description" data-bind="value: status.Description, attr: { name: 'Statuses[' + $index() + '].Description'}" />
</td>
<td style="padding-bottom:5px;">
<input type="checkbox" class="active" data-bind="value: status.Active, checked: status.Active, click: $parent.updateCheckbox, attr: { name: 'Statuses[' + $index() + '].Active'}" />
</td>
<td style="padding-bottom:5px;">
<input type="button" data-bind="click: $parent.removeStatus, visible: status.IsNew" value="Remove" />
</td>
</tr>
</tbody>
//////KNOCKOUT//////
var _viewModel = new ViewModel();
function status(index) {
this.StatusID = ko.observable('');
this.Description = ko.observable('');
this.Index = ko.observable(index);
this.Active = ko.observable(true);
this.ShowID = ko.observable(false);
this.IsNew = ko.observable(true);
return this;
};
function ViewModel() {
var self = this;
self.Statuses = ko.observableArray(convertJSONToKoObservableObject());
//self.Statuses.push(new status(0));
//Ko Functions
self.addStatus = function () {
var index = $('#StatusGrid tr:last').attr('index');
self.Statuses.push(new status(index + 1));
}
self.removeStatus = function (row) {
self.Statuses.remove(row);
}
self.updateCheckbox = function (row) {
var index = row.Index();
var checkbox = $('#StatusGrid tr').eq(index).find('[type=checkbox]');
if ($(checkbox).is(":checked")) {
$(checkbox).attr('checked', false);
row.Index(false);
}
else {
$(checkbox).attr('checked', true);
row.index(true);
}
return true;
}
}
//FUNCTION
function convertJSONToKoObservableObject() {
var json = JSON.parse('@Html.Raw(new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(Model.Statuses))');
var ret = [];
var index = 0;
$.each(json, function (i, obj) {
var newOBJ = new status(index);
newOBJ.StatusID = ko.observable(obj["StatusID"]);
newOBJ.Description = ko.observable(obj["Description"]);
newOBJ.Active = ko.observable(obj["Active"]);
newOBJ.Index = ko.observable(index);
newOBJ.ShowID = ko.observable(false);
newOBJ.IsNew = ko.observable(false);
ret.push(newOBJ);
index++;
});
return ret;
}
//BIND UP!
ko.applyBindings(_viewModel);
【问题讨论】:
标签: jquery asp.net-mvc-4 knockout.js