gpt4 book ai didi

asp.net-mvc-3 - 未捕获的类型错误 : Cannot call method 'remove' of undefined

转载 作者:行者123 更新时间:2023-12-02 05:18:36 25 4
gpt4 key购买 nike

我正在尝试将 knockout.js 与 MVC3 一起使用,但我一直收到错误消息:

Uncaught TypeError: Cannot call method 'remove' of undefined

设置是我有一个 UL 列表,我需要从中添加和删除:

<ul data-bind="foreach: Interviewees">
<li>
<div>
<a data-bind="click: $root.removeInterviewee" class="xOut"></a>
</div>
<div>
<h2>
<span data-bind="text: FirstName"></span>
<span data-bind="text: LastName"></span>
</h2>
</div>
</li>
</ul>

这是具有 knockout 内容的 javascript 部分:

function SomeThingee(Id, SomeThingeeId, firstName, lastName, title, email) {
this.Id = Id;
this.SomeThingeeId = SomeThingeeId;
this.FirstName = firstName;
this.LastName = lastName;
this.Title = title;
this.Email = email;
}

var viewModel = ko.validatedObservable({
addSomeThingee: function () {
if (!viewModel.isValid()) {
viewModel.errors.showAllMessages();
return false;
} else {
var newSomeThingee = new SomeThingee(this.Id(), 0, this.FirstName(), this.LastName(), this.Title(), this.Email());

$.ajax({
url: '@Url.Action("AddSomeThingee")',
type: "POST",
data: ko.toJSON(newSomeThingee),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (result) {
newSomeThingee.SomeThingeeId = result.message;
},
error: function (result) {

}
});

this.SomeThingees.push(newSomeThingee);
}
},
removeSomeThingee: function (item) {
this.SomeThingees.remove(item);
}
});

$(function () {
var jsonModel = '@Html.Raw(JsonConvert.SerializeObject(this.Model))';
var mvcModel = ko.mapping.fromJSON(jsonModel);

var myViewModel = new viewModel();
var g = ko.mapping.fromJS(myViewModel, mvcModel);

ko.applyBindings(g, document.getElementById("someDiv"));

});

错误发生在这一行:

this.SomeThingees.remove(item);

请注意,SomeThingees 集合由模型本身提供。 add 方法工作得很好,但是 remove 方法不起作用并给我上面列出的错误。我做错了什么?

最佳答案

问题是当 click 绑定(bind)调用 $root.removeInterviewee 时,this 被设置为数据项( $data) 而不是 View 模型 ($root)。有几种方法可以解决这个问题。可能最简单的方法是对绑定(bind)中的函数引用使用 bind

<a data-bind="click: $root.removeInterviewee.bind($root)" class="xOut"></a>

另见 Github issue进一步讨论。

关于asp.net-mvc-3 - 未捕获的类型错误 : Cannot call method 'remove' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14247354/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com