我在淘汰赛和淘汰赛映射,CustomerViewModel,WorkOrderViewModel和RepairViewModel中设置了祖父母,父,子ViewModel关系。
对于每个级别,如果记录已被修改,则标记。然后我有一个保存按钮,可以保存整个模型。保存模型的功能在祖父视图模型(CustomerViewModel)
中子级元素的示例
<input class="form-control input-sm text-right" name="RepairCost" id="RepairCost" data-bind="value: RepairCost, event: {change: flagRepairAsEdited}" />
在flagRepairAsEdited函数中是否有一种方法我可以在父/祖父母中调用SAVE函数?
非常感谢!
这是我正在使用的JS代码(简化):
var ObjectState = {
Unchanged: 0,
Added: 1,
Modified: 2,
Deleted: 3
};
var workOrderMapping = {
'WorkOrders': {
key: function (workOrders) {
return ko.utils.unwrapObservable(workOrders.WorkOrderId);
},
create: function (options) {
return new WorkOrderViewModel(options.data);
}
},
'Repairs': {
key: function (repairs) {
return ko.utils.unwrapObservable(repairs.RepairId);
},
create: function (options) {
return new RepairViewModel(options.data);
}
}
};
RepairViewModel = function (data) {
var self = this;
ko.mapping.fromJS(data, workOrderMapping, self);
self.flagRepairAsEdited = function () {
if (self.ObjectState() != ObjectState.Added) {
self.ObjectState(ObjectState.Modified);
}
//WOULD LOVE TO CALL SAVE FUNCTION HERE
return true;
}
;
}
WorkOrderViewModel = function (data) {
var self = this;
ko.mapping.fromJS(data, workOrderMapping, self);
self.flagWorkOrderAsEdited = function () {
if (self.ObjectState() != ObjectState.Added) {
self.ObjectState(ObjectState.Modified);
}
//WOULD LOVE TO CALL SAVE FUNCTION HERE
return true;
}
;
}
CustomerViewModel = function (data) {
var self = this;
ko.mapping.fromJS(data, workOrderMapping, self);
self.save = function () {
$.ajax({
url: "/Customers/Save/",
type: "POST",
data: ko.toJSON(self),
contentType: "application/json",
success: function (data) {
ko.mapping.fromJS(data.customerViewModel, workOrderMapping, self);
if (data.newLocation != null)
window.location = data.newLocation;
},
});
},
self.flagCustomerAsEdited = function () {
if (self.ObjectState() != ObjectState.Added) {
self.ObjectState(ObjectState.Modified);
}
return true;
}
;
}
答案 0 :(得分:3)
有两种方法可以做到这一点
a)将viewModels作为子flagRepairAsEdited
函数的参数传递:
data-bind="value: RepairCost, event: {change: flagRepairAsEdited.bind($data, $parent, $root)}"
b)在子viewModel
中保存父viewModel的链接WorkOrderViewModel = function (data, parent) {
this.parent = parent;
...
}
使用parent.flagWorkOrderAsEdited
和parent.parent.flagWorkOrderAsEdited
保存父视图模型和祖父母视图模型