Reputation: 547
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)
Upvotes: 1
Views: 7010
Reputation: 1307
You can add a function to your view model, removeTag, like the following:
self.removeTag = function(tag) { self.tags.remove(tag); })
Upvotes: 1
Reputation: 126
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.net/Ng39n/
Upvotes: 1
Reputation: 3700
Your 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)
Upvotes: 3