3
我遇到了一個問題,即刪除可觀察數組中的對象。我有一個removeItemFromQueue
函數應該從隊列中刪除選定的對象。從observableArray中刪除對象
This example表明,如果你添加了一堆的項目到隊列中,然後取出一個,它消除了所有的人:
<h3>Items:</h3>
<ul data-bind="template: {name:'itemsTemplate', foreach: items}"></ul>
<h3>Queue:</h3>
<ul data-bind="template: {name:'queueTemplate', foreach: queue}"></ul>
<script id="itemsTemplate" type="text/x-jquery-tmpl">
<li>
<a href="#">${$data.title}</a> by <a href="#">${$data.description}</a>
<button data-bind="click: function() {viewModel.removeItemFromPage($data);}">Remove From Page</button>
<button data-bind="click: function() {viewModel.addItemToQueue($data);}">Add To Queue</button>
</li>
</script>
<script id="queueTemplate" type="text/x-jquery-tmpl">
<li>
<a href="#">${$data.title}</a> by <a href="#">${$data.description}</a>
<button data-bind="click: function() {viewModel.removeItemFromQueue($data);}">Remove From Queue</button>
</li>
</script>
這是JavaScript:
function Item(title, description) {
this.title = ko.observable(title);
this.description = ko.observable(description);
}
var viewModel = {
items: ko.observableArray([
new Item("one", "one description")
]),
queue: ko.observableArray([]),
addItemToQueue: function (item) {
this.queue.push(item);
},
removeItemFromPage: function (item) {
this.items.remove(item);
},
removeItemFromQueue: function (item) {
this.queue.remove(item);
}
};
ko.applyBindings(viewModel);
我發現this workaround使用ko.toJS(item)
在addItemToQueue
功能:
<h3>Items:</h3>
<ul data-bind="template: {name:'itemsTemplate', foreach: items}"></ul>
<h3>Queue:</h3>
<ul data-bind="template: {name:'queueTemplate', foreach: queue}"></ul>
<script id="itemsTemplate" type="text/x-jquery-tmpl">
<li>
<a href="#">${$data.title}</a> by <a href="#">${$data.description}</a>
<button data-bind="click: function() {viewModel.removeItemFromPage($data);}">Remove From Page</button>
<button data-bind="click: function() {viewModel.addItemToQueue($data);}">Add To Queue</button>
</li>
</script>
<script id="queueTemplate" type="text/x-jquery-tmpl">
<li>
<a href="#">${$data.title}</a> by <a href="#">${$data.description}</a>
<button data-bind="click: function() {viewModel.removeItemFromQueue($data);}">Remove From Queue</button>
</li>
</script>
和這個Javascript:
function Item(title, description) {
this.title = ko.observable(title);
this.description = ko.observable(description);
}
var viewModel = {
items: ko.observableArray([
new Item("one", "one description")
]),
queue: ko.observableArray([]),
addItemToQueue: function (item) {
this.queue.push(ko.toJS(item));
},
removeItemFromPage: function (item) {
this.items.remove(item);
},
removeItemFromQueue: function (item) {
this.queue.remove(item);
}
};
ko.applyBindings(viewModel);
是否有更簡單的方法?
另外,這裏的購物車示例看起來使用與我的第一個示例類似的代碼,但不會遇到與刪除項目相同的問題。我有點困惑。
以下是購物車示例:http://knockoutjs.com/examples/cartEditor.html – horizens