jmo*_*era 2 asp.net-mvc-3 knockout-mapping-plugin knockout-2.0 knockout.js
我试图使用knockout.js与MVC3,我继续得到错误:
未捕获的TypeError:无法调用undefined的方法'remove'
设置是我有一个我需要添加和删除的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>
Run Code Online (Sandbox Code Playgroud)
这是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"));
});
Run Code Online (Sandbox Code Playgroud)
此行发生错误:
this.SomeThingees.remove(item);
Run Code Online (Sandbox Code Playgroud)
请注意,SomeThingees集合由模型本身提供.add方法完全正常,但remove方法不起作用,并给我上面列出的错误.我究竟做错了什么?
问题是当click
绑定调用时$root.removeInterviewee
,this
设置为data-item($data
)而不是view-model($root
).有几种方法可以解决这个问题.可能最简单的方法是bind
在绑定中使用函数引用.
<a data-bind="click: $root.removeInterviewee.bind($root)" class="xOut"></a>
Run Code Online (Sandbox Code Playgroud)
另请参阅此Github问题以供进一步讨论.
归档时间: |
|
查看次数: |
2001 次 |
最近记录: |