从Knockout可观察数组

时间:2016-06-08 00:27:31

标签: javascript jquery arrays knockout.js

我有以下淘汰模型的结构。它包含一个可观察的数组,该数组又包含一个对象。

   function ViewModel() {
    var self = this;

    self.newItem = ko.observable({        
        manufacturer: ko.observable(),
        itemnumber: ko.observable(),
        itemDescription: ko.observable()    

    });
    self.AllItems = ko.observableArray();      

    self.addItem = function() { 
     self.newItem().manufacturer("test");    
     self.newItem().itemDescription("data");

    self.AllItems.push(self.newItem); 

    };
    self.removeItem = function(data) { 
        self.AllItems.remove(data);
    };
}

第一个问题:通过这个脚本,我在文本框中输入一个新的项目编号,然后单击添加项目,将带有文本框中项目编号的新项目添加到可观察数组,但是当我更改项目编号并点击添加时它会更改数组中的所有itemnumber。如何在数组中包含唯一数据。

第二个问题:我需要从数组中删除特定项目,但它不会删除它。有人可以告诉我如何根据itemnumber属性删除可观察数组中的项目。

<input type="text" data-bind="value: newItem().itemnumber"/>
<div>
    Items: <button data-bind="click: addItem">Add Item</button>
</div>
<div>
    <table>
        <tbody data-bind="template: { name: 'itemTemplate', foreach: AllItems }"></tbody>
    </table>
</div>
<script type="text/html" id="itemTemplate">
    <tr>
        <td>
            <input data-bind="value: itemnumber" />
            <a href="#" data-bind="click: $parent.removeItem">Remove Item</a>
        </td>
    </tr>
</script>

我已经创建了这个小提琴,可以快速查看问题。刚开始学习淘汰赛,所以感谢任何帮助。

http://jsfiddle.net/N3JaW/138/

1 个答案:

答案 0 :(得分:2)

尝试以下方法添加新项目,这将解决您的第一个问题: -

HTML代码

<input type="text" id="textBox" data-bind="value : textBoxVal"/>
<div>
    Items: <button data-bind="click: addItem">Add Item</button>
</div>
<div>
<table>
    <tbody data-bind="template: { name: 'itemTemplate', foreach: AllItems }"></tbody>
</table>
</div>
<script type="text/html" id="itemTemplate">
<tr>
    <td>
        <input data-bind="value: itemnumber" />
        <a href="#" data-bind="click: $parent.removeItem">Remove Item</a>
    </td>
</tr>
</script>

JS代码: -

function ViewModel() {
var self = this;

self.newItem = ko.observable({        
    manufacturer: "",
    itemnumber: "",
    itemDescription: ""   

});

 self.textBoxVal = ko.observable();
 self.AllItems = ko.observableArray();      

self.addItem = function() { 
 self.newItem().manufacturer= "test"; 
 self.newItem().itemDescription= "data";
 self.newItem().itemnumber = self.textBoxVal();

self.AllItems.push(self.newItem); 

};
self.removeItem = function(data) { 
    self.AllItems.remove(data);
};
}
$(document).ready(function() {ko.applyBindings(new ViewModel()); });

您的第一个问题是因为,每次尝试添加新项目时,您都会更改itemNumber的值,这是一个可观察的值。

当它的值被更改时,可以在每个绑定的位置更改可观察值。

相反,你需要创建新对象并进入observableArray。

请参阅doc以了解有关observableArray的更多信息。

对于您的第二个问题更改removeItem,如下所示: -

 self.removeItem = function(data) {
var dtIndex = self.AllItems.indexOf(data); //Get the index of the object you want to remove.
    self.AllItems.splice(dtIndex, 1); //Then do splice
};

您可以参考上述文档,了解如何使用splice

根据评论中的建议进行编辑: -

编辑回答click here的工作代码。

希望这能解决您的问题。

相关问题