KnockoutJS删除动态绑定

KnockoutJS Remove dynamic bindings

本文关键字:动态绑定 删除 KnockoutJS      更新时间:2023-09-26

在其他人的帮助下,我成功地获得了一个原型,可以动态添加新的输入,并在旁边添加特定的输入设置。然而,我一直在努力掌握如何动态删除我添加的内容。有什么想法吗?

HTML

<div class="input-row" data-bind="foreach: inputItems">                 
    <div class="input-row-item">                
        <div>   
            <label data-bind="text: label"></label>                 
            <input data-bind="attr:{ name: name, placeholder: placeholder, disabled: disabled() === 'true', value: value, type: type }">                    
        </div>
        <div>
            <input type="text" class="nb-remove" data-bind="value: label" placeholder="input label">
            <input type="text" value="text" class="nb-remove" data-bind="value: type" placeholder="input type">
            <input type="text" class="nb-remove" data-bind="value: name" placeholder="input name">
            <input type="text" class="nb-remove" data-bind="value: placeholder" placeholder="input placeholder">
            <input type="text" class="nb-remove" data-bind="value: disabled" placeholder="input disabled">
            <input type="text" class="nb-remove" data-bind="value: value" placeholder="input value">
        </div>
        <div>
            <button data-bind="click: removeInput">Remove this</button>
        </div>
    </div>                  
</div>  

JS-

$(function(){
    var InputItem = function InputItem(label, type, name, placeholder, disabled, value) {
        this.label          = ko.observable(label);
        this.type           = ko.observable(type);
        this.name           = ko.observable(name);
        this.placeholder    = ko.observable(placeholder);
        this.disabled       = ko.observable(disabled);
        this.value          = ko.observable(value);
    }
    var ViewModel = function ViewModel() {
      var that = this;
      this.inputItems = ko.observableArray([]);          
      this.addInput = function addInput() {
        that.inputItems.push(new InputItem());
      };
      this.removeInput = function removeInput(){
        //remove input here
      }
    }
    ko.applyBindings(new ViewModel());
});

您应该尝试类似的东西

视图模型:

         var ViewModel = function() {
              var that = this;
              that.inputItems = ko.observableArray([new InputItem()]);  
              that.addInput = function () {
                that.inputItems.push(new InputItem());
              };
              that.removeInput = function (item){
                that.inputItems.remove(item);
              }
            }
         ko.applyBindings(new ViewModel());

工作小提琴此处

少数建议:

1) 当您分配var that=this时,您尝试在vm 中一致地使用that

2) 您可以像这样创建一个函数名var fun=function(),也可以像这样做function fun(){//blah blah}