0

我正在使用 MVC4 填充复杂的视图模型。我这样填充

var job = @Html.Raw(Json.Encode(Model.job));
var customer = @Html.Raw(Json.Encode(Model.customer));
var listTasks = @Html.Raw(Json.Encode(Model.Tasks));
var estimateMaterials = @Html.Raw(Json.Encode(Model.estimateMaterials));
var estimate = @Html.Raw(Json.Encode(Model.estimate));

var JobPost = {
    customer: customer,
    job: job,
    listTasks: ko.observableArray(listTasks),
    estimateMaterials: ko.observableArray(estimateMaterials),
    estimate: ko.observable()
};
ko.applyBindings(JobPost,  document.getElementById("update-job-form"));

现在,对象estimateMaterials被填充到一行。对于那一行,我想像这样添加Remove到每一行和Add button表格的底部

桌子的图像

然后我看到了,rniemeyer在轻松添加/删除行方面非常出色。
分叉的小提琴是:http: //jsfiddle.net/codovations/tDV9k/

在那有一个像这样的片段

self.addLine = function() { self.lines.push(new CartLine()) };
self.removeLine = function(line) { self.lines.remove(line) };

我想对我的可观察数组实现类似的东西
estimateMaterials: ko.observableArray(estimateMaterials)

是否可以添加这样的方法?

PS:我通过使用jquery分别克隆行/删除最近的tr来添加/删除。我正在寻找一种更清洁的方式。

更新:

我在这里面临的主要问题是如何访问observableArray

4

1 回答 1

1

我可能没有正确理解您的问题,请查看以下内容,如果您有任何问题,请告诉我

function EstimateMaterialLine() {
    var self = this;
    self.EstMatlID = ko.observable();
    //other observables to follow
}
var job = @Html.Raw(Json.Encode(Model.job));
var customer = @Html.Raw(Json.Encode(Model.customer));
var listTasks = @Html.Raw(Json.Encode(Model.Tasks));
var estimateMaterials = @Html.Raw(Json.Encode(Model.estimateMaterials));
var estimate = @Html.Raw(Json.Encode(Model.estimate));

var JobPostViewModel = function(){
    var self = this;
    self.customer = ko.observable(customer);
    self.job = ko.observable(job);
    self.listTasks = ko.observableArray(listTasks);
    self.estimateMaterials = ko.observableArray(estimateMaterials);
    self.estimate = ko.observable(estimate);
    self.removeEstimateMaterial = function(line) { 
        self.estimateMaterials.remove(line) 
    };
    self.addEstimateMaterial = function() { 
        self.estimateMaterials.push(new EstimateMaterialLine()) 
    };
};
var model = new JobPostViewModel();
ko.applyBindings(model,  document.getElementById("update-job-form"));

所以假设你有一张桌子,那么你可以像这样使用它:

<table data-bind="foreach: estimateMaterials">
    <tr>
       <td> <input type="button" value="delete" data-bind="click: $root.removeEstimateMaterials"/> </td>
    <tr>
</table>
<input type="button" value="Add" data-bind="click: $root.addEstimateMaterials"/>
于 2013-10-02T12:19:02.177 回答