模型
public class model
{
public int modelid { get; set; }
public string name { get; set; }
public List<childModel> childModel{ get; set; }
}
public class childModel
{
public int childModelid { get; set; }
public string childname { get; set; }
}
java脚本
@{
var datam = new JavaScriptSerializer().Serialize(Model);
}
var helloWorldModel = {
model: ko.mapping.fromJS(@Html.Raw(datam)),
dele: function (models) {
helloWorldModel.model.remove(models);
}
}
ko.applyBindings(helloWorldModel);
HTML
<span data-bind="foreach:model">
<span data-bind="text : name"></span>
<span data-bind="foreach:childmodel">
<input type="text" data-bind="value:childname" />
</span>
<input type="button" data-bind="click:$parent.dele" value="delete parent" />
</span>
所以我可以删除模型,但有没有办法删除这个结构的子模型? 像这样的东西:
deleChildModel: function (Childmodels) {
helloWorldModel.model.childModel.remove(Childmodels);
}
我可以将添加的modelid添加到ChildModel,然后使用
deleChildModel: function (Childmodels) {
helloWorldModel.model()[Childmodels.modelid].childModel.remove(Childmodels);
}
但我正在寻找更简单的东西
答案 0 :(得分:2)
您可以使用bind
让按钮将父级和子级传递给deleteChild函数。 bind
的第一个参数提供了调用结果函数的上下文(this
)。
var models = [{
name: 'One',
childmodel: [{
childname: "SubOne"
}]
}, {
name: 'Two',
childmodel: [{
childname: "SubTwo"
}]
}];
var vm = (function() {
var self = {
model: ko.mapping.fromJS(models),
dele: function(item) {
self.model.remove(item);
},
deleteChild: function(child) {
var parent = this;
parent.childmodel.remove(child);
}
};
return self;
}());
ko.applyBindings(vm);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/knockout.mapping/2.4.1/knockout.mapping.min.js"></script>
<span data-bind="foreach:model">
<span data-bind="text : name"></span>
<span data-bind="foreach:childmodel">
<input type="text" data-bind="value:childname" />
<button data-bind="click:$root.deleteChild.bind($parent)">Delete Child</button>
</span>
<input type="button" data-bind="click:$parent.dele" value="delete parent" />
</span>