Reputation: 71
I working with Knockout and Asp.net for a project and I have some problem to add a delete action with Knockout
Everything was working fine, and the databinding doing well. But when I try to add a delete function I get this error :
JavaScript runtime error: Unable to get property 'deleteArticle' of undefined or null reference
My javascript :
// Class to represent an article
function article(data) {
//var self = this;
this.id = ko.observable(data.OrderId);
this.Type = ko.observable(data.Type);
this.Price = ko.observable(data.Price);
this.Quantity = ko.observable(data.Quantity);
}
function viewModel() {
var self = this;
self.Articles = ko.observableArray([]);
$.getJSON("@Url.Action("../home/AjaxArticles")", function (allData) {
var mappedArticles = $.map(allData, function (item) { return new article(item) });
self.Articles(mappedArticles);
});
// Delete an article
self.deleteArticle = function (ArticleData) {
self.Articles.remove(ArticleData);
};
self.MyMoney = ko.observableArray([]);
$.getJSON("@Url.Action("../home/AjaxMoney")", function (allData) {
var mappedMoney = $.map(allData, function (item) { return new Money(item) });
self.MyMoney(mappedMoney);
});
}
$(document).ready(function () {
ko.applyBindings(viewModel);
});
And the HTML part where I use knockout:
<tbody data-bind="foreach: Articles">
<tr>
<td data-bind="text: id"></td>
<td data-bind="text: Price"></td>
<td data-bind="text: Type"></td>
<td data-bind="text: Quantity"></td>
<td><a href='#' data-bind="click: $root.deleteArticle">Cancel</a></td>
</tr>
</tbody>
What do I do wrong ?
Upvotes: 0
Views: 86
Reputation: 3702
You didn't instantiate your viewmodel correctly (instead, you passed in the function-object itself). When you apply your KO bindings, pass in a new instance of your viewmodel
, like so:
ko.applyBindings(new viewModel());
Upvotes: 1