【问题标题】:Removing and modifying items from ko.observableArray从 ko.observableArray 中删除和修改项目
【发布时间】:2013-10-20 05:24:44
【问题描述】:

我已经提交了我的 MVC4 代码here 的 sn-p。我希望“减号”按钮删除它所属的行,然后遍历数组并将输入名称调整为连续的。我想我需要它是顺序的才能使用 MVC4 模型绑定。

我的问题是,如何识别刚刚单击了哪个按钮,以及它属于数组中的哪个对象?请问有什么想法吗?我对淘汰赛完全陌生,所以我什至不确定这是否是最好的方法。

这是我的视图模型:

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 () {

    };
}

这是我的标记:

<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>

【问题讨论】:

    标签: javascript jquery asp.net-mvc asp.net-mvc-4 knockout.js


    【解决方案1】:

    如果您已将点击处理程序绑定到按钮,则可以执行以下操作

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

    data 将是对绑定到当前行的对象的引用

    【讨论】:

    • 我认为如果在对象中定义了动作,这将起作用,但事实并非如此。 removeRow 函数在 $parent 中。请参考jsFiddle sn-p。
    • @DanyW 即使您在$parent 上有removeRow,此解决方案也应该可以工作,因为KO 将“当前”项目作为第一个参数自动传递到点击处理程序中,请参见此处的实际操作:@ 987654321@
    • Ach...确实有效。我复制并粘贴了绑定代码,忘记将addRow 更改为removeRow
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-23
    • 2015-10-29
    • 2014-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多