使用add / remove绑定表的数据绑定问题

时间:2013-10-02 07:13:14

标签: knockout.js knockout-mapping-plugin

我正在使用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

Image of the table

然后我看到,rniemeyer wonderful fiddle很容易添加/删除行 分叉小提琴是: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)

这可以添加这样的方法吗?

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

更新

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

中的对象

1 个答案:

答案 0 :(得分: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"/>