我有下一个代码:
@{
ViewBag.Title = "Index";
}
@model KO_MVC.Models.IndividualViewModel
<ul data-bind="foreach: Individuals">
<li>
<input type= "text" data-bind ="value: Name"/>
<button data-bind="click: remove"> remove</button>
<label> <input type="checkbox" data-bind ="checked: HasAlias" /> </label>
<input type ="text" data-bind="value: Alias, visible: HasAlias">
</li>
</ul>
<button data-bind="click: addItem"> add new</button>
<script>
var data = @Html.Raw(new System.Web.Script.
Serialization.JavaScriptSerializer().Serialize(Model));
var viewModel = function ()
{
var self = this;
ko.mapping.fromJS(data, {}, self);
self.Individuals = ko.observableArray(self.Individuals());
self.addItem = function() {
self.Individuals.push({Name:"newIndividual", HasAlias: false, Alias:"" });
};
self.remove = function(data) {
self.Individuals.remove(data);
};
};
ko.applyBindings(viewModel);
</script>
当我向Individuals数组中添加一个新项目时,该项目显示正常,但该复选框不执行任何操作,预期结果是显示文本框
答案 0 :(得分:0)
foreach中的上下文存在问题,因为你有addItem并在父上下文中删除,绑定将有 $ parent 。
HTML: -
<ul data-bind="foreach:Individuals">
<li>
<input type="text" data-bind="value: Name" />
<button data-bind="click: $parent.remove">remove</button>
<label>
<input type="checkbox" data-bind="checked: HasAlias" />
</label>
<input type="text" data-bind="value: Alias, visible: HasAlias" />
</li>
</ul>
<button data-bind="click: addItem">add new</button>
JS: -
var viewModel = function () {
var self = this;
self.Individuals = ko.mapping.fromJS(data);
self.addItem = function () {
self.Individuals.push({
Name: "newIndividual",
HasAlias: false,
Alias: ""
});
};
self.remove = function (data) {
self.Individuals.remove(data);
};
};
ko.applyBindings(new viewModel());