我正在使用knockout来修改ui。我可以通过单击每个文本上的关闭按钮“x”来从屏幕上删除文本。
当我点击保存时,我希望所有剩余的文本都保留在屏幕上,没有关闭按钮,文本周围没有输入框。如何通过淘汰赛实现这一目标。我的代码在
之下
var data = { Name: "Test",
Items: ["sample1", "sample2", "sample3","DESIGN"]
};
function ViewModel(data) {
var self = this;
self.Name = ko.observable(data.Name);
self.Items = ko.observableArray(ko.utils.arrayMap(data.Items, function(item) {
return { value: ko.observable(item) };
}));
self.addItem = function() { self.Items.push({ value: ko.observable("") }); };
self.removeItem = function(data) {
self.Items.remove(data);
};
self.SaveItem = function() { self.Items.push({ value: ko.observable("") }); };
self.SaveItem = function(data) {
self.Items.save(data);
};
}
$(document).ready(function() {ko.applyBindings(new ViewModel(data)); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.0.0/knockout-min.js"></script>
<div>
Name: <span data-bind="text: Name"></span>
</div>
<div>
Items: <button data-bind="click: addItem">Add Item</button>
</div>
<div>
<table>
<tbody data-bind="template: { name: 'itemTemplate', foreach: Items }"></tbody>
</table>
</div>
<button data-bind="click: SaveItem">SAVE</button>
<script type="text/html" id="itemTemplate">
<tr>
<td>
<input data-bind="value: value" />
<a href="#" data-bind="click: $parent.removeItem">X</a>
</td>
</tr>
</script>
答案 0 :(得分:1)
您需要设置一个observable来告诉视图何时保存这些项目,然后用不同的标记替换输入和“X”。
var data = { Name: "Test",
Items: ["sample1", "sample2", "sample3","DESIGN"]
};
function ViewModel(data) {
var self = this;
self.saved = ko.observable(false);
self.Name = ko.observable(data.Name);
self.Items = ko.observableArray(ko.utils.arrayMap(data.Items, function(item) {
return { value: ko.observable(item) };
}));
self.addItem = function() { self.Items.push({ value: ko.observable("") }); };
self.removeItem = function(data) {
self.Items.remove(data);
};
self.SaveItem = function() { self.Items.push({ value: ko.observable("") }); };
self.SaveItem = function(data) {
//self.Items.save(data); I have no idea what you are doing here
self.saved(true);
};
}
$(document).ready(function() {ko.applyBindings(new ViewModel(data)); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.0.0/knockout-min.js"></script>
<div>
Name: <span data-bind="text: Name"></span>
</div>
<div>
Items: <button data-bind="click: addItem">Add Item</button>
</div>
<div>
<table>
<tbody data-bind="template: { name: 'itemTemplate', foreach: Items }"></tbody>
</table>
</div>
<button data-bind="click: SaveItem">SAVE</button>
<script type="text/html" id="itemTemplate">
<tr>
<td data-bind="visible: !$parent.saved()">
<input data-bind="value: value" />
<a href="#" data-bind="click: $parent.removeItem">X</a>
</td>
<td data-bind="visible: $parent.saved()">
<span data-bind="text: value"></span>
</td>
</tr>
</script>