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>
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>
Share
Improve this question
edited May 20, 2014 at 13:06
Hoppe
asked Apr 20, 2012 at 19:58
HoppeHoppe
6,80518 gold badges64 silver badges122 bronze badges
1 Answer
Reset to default 17When 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.