Please see code (Using knockout.js over ASP MVC 3):
self.tags = ko.utils.arrayMap(@Html.Raw(new JavaScriptSerializer().Serialize(Model.Tags)), function(tag) {
return {
label: tag.Name,
value: tag.id
};
});
self.addTag = function(event, ui){
$(event.target).val("");
var tag = ui.item.label;
var id = ui.item.value;
self.selectedTags.push("id: " + id + ", Name: " + tag);
//Delete selected tag here from list
return false;
}
The question is, how can I remove from tags? (I tried using remove(), I encounter an error. But when I try pop(), its successful)
Please see code (Using knockout.js over ASP MVC 3):
self.tags = ko.utils.arrayMap(@Html.Raw(new JavaScriptSerializer().Serialize(Model.Tags)), function(tag) {
return {
label: tag.Name,
value: tag.id
};
});
self.addTag = function(event, ui){
$(event.target).val("");
var tag = ui.item.label;
var id = ui.item.value;
self.selectedTags.push("id: " + id + ", Name: " + tag);
//Delete selected tag here from list
return false;
}
The question is, how can I remove from tags? (I tried using remove(), I encounter an error. But when I try pop(), its successful)
Share Improve this question edited Apr 18, 2012 at 11:22 Christofer Eliasson 33.9k7 gold badges77 silver badges103 bronze badges asked Apr 18, 2012 at 11:16 Vinny MarquezVinny Marquez 5473 silver badges12 bronze badges 3-
1
If
.pop()
works, why not use it? – Christofer Eliasson Commented Apr 18, 2012 at 11:21 - .pop() only gets the last item you entered right? i want to be able to delete any item in the array. – Vinny Marquez Commented Apr 18, 2012 at 12:34
- I see, your right, in that case pop wouldn't work. – Christofer Eliasson Commented Apr 18, 2012 at 12:40
3 Answers
Reset to default 3Your tags array is normal array, not observable array, it will have no remove method.
Knockout has helper for normal arrays
ko.utils.arrayRemoveItem(array, itemToRemove)
or you can use splice (actually ko.utils.arrayRemoveItem uses splice)
Normally you can remove an item from a javascript array with splice.
Pop will not work as it only removes the last inserted value.
var a = [1,2,3] a.splice(1,1); # remove one element at position 1 => [1,3]
you can use this with knockout if you want.
knockout also has some api's like array.remove(function(a){ return a.id === 1; }) that returns all elements that have the id 1.
EDIT: As an example you can look at this JsFiddle http://jsfiddle/Ng39n/
You can add a function to your view model, removeTag, like the following:
self.removeTag = function(tag) { self.tags.remove(tag); })