简体   繁体   中英

Removing and modifying items from ko.observableArray

I have put up a snippet of my MVC4 code here . 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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