Reputation: 5760
I have a small page which list data coming Knockout array and with every item I have delete link. Clicking on delete link item next to link is deleted from array but I can't delete newly added item.
JSFiddler: enter link description here
Here is my code:
<input type="text" data-bind="value: tagToAdd, valueUpdate: 'afterkeydown'" />
<button data-bind="click: addTag">+ Add</button>
<div data-bind="foreach: tags">
<span data-bind="text: Name"></span>
<a href="#" class="deleteItm">Delete </a>
</div>
Here is JS code:
var data = [
{ Id: 1, Name: "abc" },
{ Id: 2, Name: "def" },
{ Id: 3, Name: "ghi" },
{ Id: 4, Name: "jkl" }
];
var viewModel = function () {
var self = this;
//data
self.tags = ko.observableArray(data);
self.tagToAdd = ko.observable();
//behaviour
self.addTag = function () {
self.tags.push({ Name: self.tagToAdd() });
self.tagToAdd("");
};
};
$(function () {
var vm = new viewModel();
ko.applyBindings(vm);
$(".deleteItm").on("click", function () {
var itmToRemove = ko.dataFor(this);
console.log(itmToRemove);
vm.tags.remove(itmToRemove);
ko.applyBindings(vm);
});
Question / Issue : I need to make this code deleting newly (dynamically) added items. If I add a new item and delte it do not work but delete items coming from JS
Edit: I just have checked it do not work just in FF
Upvotes: 0
Views: 123
Reputation: 7958
The best way is to not use jQuery itself but to use knockout to remove the item.
self.deleteItem = function(item) {
self.tags.remove(item)
};
<a href="#" class="deleteItm" data-bind="click: $root.deleteItem">Delete </a>
Upvotes: 1
Reputation: 82251
You need to use event delegation for binding event to dynamically added DOM:
Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.
$("body").on("click",'.deleteItm', function () {
var itmToRemove = ko.dataFor(this);
console.log(itmToRemove);
vm.tags.remove(itmToRemove);
ko.applyBindings(vm);
});
Upvotes: 0