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 for this
. An easy way is to use .bind
.
It would look like:
this.removeExpertise = function (expertise) {
this.expertise.remove(expertise);
}.bind(this);
Also, you will want expertise
to be an observableArray
rather than an observable
, as an observableArray
exposes array manipulation methods including a remove
function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With