简体   繁体   English

尝试使用Knockout添加删除数据绑定功能时出错

[英]Error when trying to add a delete databind function using Knockout

I working with Knockout and Asp.net for a project and I have some problem to add a delete action with Knockout 我使用Knockout和Asp.net进行项目,但是在使用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 JavaScript运行时错误:无法获取未定义或空引用的属性“ deleteArticle”

My javascript : 我的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: 以及我使用剔除的HTML部分:

    <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 ? 我做错了什么?

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绑定时,传入一个新的viewmodel实例,如下所示:

ko.applyBindings(new viewModel());

See fiddle 见小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM