KnockoutJS删除动态绑定

时间:2015-03-04 14:18:35

标签: javascript jquery knockout.js

我设法让原型在其他人的帮助下工作,动态添加新输入,并在其旁边显示特定的输入设置。但是,我一直试图抓住如何删除我动态添加的内容。有什么想法吗?

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>  

THE 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());
});

1 个答案:

答案 0 :(得分:1)

你应该尝试这样的事情

查看型号:

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

工作小提琴 here

几条建议:

1)在您指定var that=this时,您尝试在vm中始终使用that

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