Using KnockoutJS, how can I remove an item from an observable array? I want to be able to click on the listitem, and remove the item from the array (and thereby the list).
The code sample below reports: 'this.expertise is undefined'.
Do I need to define some sort of expertise object, and then call it from within there?
<ul data-bind="foreach: expertise">
<li data-bind="text: Key, click: $parent.removeExpertise"></li>
</ul>
<script type="text/javascript">
$(function () {
function AppViewModel() {
this.removeExpertise = function (expertise) {
this.expertise.remove(expertise);
};
this.expertise = ko.observable([
{ Key: 'Charles', Value: 'Charlesforth' },
{ Key: 'Denise', Value: 'Dentiste' }
]);
}
// Activates knockout.js
jQuery(document).ready(function () {
ko.applyBindings(new AppViewModel());
});
});
</script>
When you call a method from the child,
this
will be set to the child rather than$parent
.There are many ways to ensure that
removeExpertise
is called with the appropriate value forthis
. An easy way is to use.bind
.It would look like:
Also, you will want
expertise
to be anobservableArray
rather than anobservable
, as anobservableArray
exposes array manipulation methods including aremove
function.