简体   繁体   English

从ko.observableArray移除和修改项目

[英]Removing and modifying items from ko.observableArray

I have put up a snippet of my MVC4 code here . 我都忍了我的MVC4代码片段在这里 I would like the "minus" button to remove the row it belongs to, then goes through the array and adjust the input names to be sequential. 我想使用“减号”按钮删除它所属的行,然后遍历数组并将输入名称调整为连续的。 I think I will need it to be sequential to work with MVC4 model binding. 我想我需要按顺序使用MVC4模型绑定。

My problem is, how do I identify which button has just been clicked, and which object in the array it belongs to? 我的问题是,如何确定刚刚单击了哪个按钮,以及该按钮属于数组中的哪个对象? Any ideas please? 有什么想法吗? I'm completely new to knockout so I'm not even sure if this is the best way to do it. 我是淘汰赛的新手,所以我什至不确定这是否是最好的方法。

This is my viewmodel: 这是我的视图模型:

function ViewModel() {
    this.breeders = ko.observableArray([{
        keyName: ko.observable("Breeders[0].Key"),
        valueName: ko.observable("Breeders[0].Value"),
        canAdd: ko.observable(true),
        canRemove: ko.observable(true)
    }]);

    this.addRow = function () {
        var next = this.breeders().length;
        this.breeders.push({
            keyName: ko.observable("Breeders[" + next.toString() + "].Key"),
            valueName: ko.observable("Breeders[" + next.toString() + "].Value"),
            canAdd: ko.observable(true),
            canRemove: ko.observable(true)
        });
    };

    this.removeRow = function () {

    };
}

And this is my markup: 这是我的标记:

<div class="form-group">
    <div id="breedersFormsContainer" data-bind="template: {name: 'breederForm', foreach: breeders}"></div>
</div>

<script type="text/html" id="breederForm">
    <div class="col-lg-offset-3">
        <span class="col-lg-1 control-label">Reg: </span><span class="col-lg-2"><input data-bind="attr: {name: keyName}" type="text" class="form-control" /></span>
        <span class="col-lg-1 control-label">Name: </span><span class="col-lg-6"><input data-bind="attr: {name: valueName}" type="text" class="form-control" /></span>
        <button type="button" class="btn btn-default" data-bind="enable: canRemove"><span class="glyphicon glyphicon-minus">-</span></button>
        <button type="button" class="btn btn-default" data-bind="enable: canAdd, click: $parent.addRow.bind($parent)"><span class="glyphicon glyphicon-plus">+</span></button>
    </div>
</script>

If you have bound the click handler to the button, you can do the following 如果已将点击处理程序绑定到按钮,则可以执行以下操作

this.removeRow = function (data) {
    yourObservableArray.remove(data);
    };

data will be a reference to the object bound to the current row 数据将是对绑定到当前行的对象的引用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM