gpt4 book ai didi

javascript - 传递一个函数,该函数在提交期间返回 ko.computed 错误的值

转载 作者:行者123 更新时间:2023-11-29 19:55:58 27 4
gpt4 key购买 nike

我在使用 knockout js 提交表单时遇到问题。

我收到错误消息“传递一个返回 ko.computed 值的函数。”

代码如下:

 (function(records,$,undefined){
records.models={
student:function(data){
var self=this;
self.id=ko.observable(data.id);
self.fname=ko.observable(data.fname);
self.lname=ko.observable(data.lname);
if(data.initial==='undefined'||data.initial===null){
self.initial=ko.observable("");
}else{
self.initial=ko.observable(data.initial);
}
self.fullname=ko.computed(function(){
return self.fname()+" "+" "+self.initial()+" "+self.lname();
});
},
students_model:function(){
var self=this;
self.selectedStudent=ko.observable();
self.students=ko.observableArray([]);
getStudents();

self.save=function(){
var form=$("#student-form");
$.ajax({
type:"POST",
url:"/Student/create",
data:ko.toJSON(form[0]), //This line here is the exact point of failue
success:function(response){
records.general.handleSuccess(response);
if(response.status){
getStudents();
}
}

});
return false;
};
function getStudents(){
$.getJSON("/Student/data",function(result){
var mapped=$.map(result,function(item){
return new records.models.student(item);});
self.students(mapped);
});
}
}
};
return records;
}(window.records=window.records||{},jQuery));

HTML

@using (Ajax.BeginForm("Create", "Student",
new AjaxOptions
{
HttpMethod = "Post"
},
new { @class = "student-form", name = "student-form", id = "student-form" }))
{
<input type="text" data-bind="value:$root.fname" id="student.fname" name="student.fname" />
<input type="text" data-bind="value:$root.lname" id="student.lname" name="student.lname"/>
<input type="text" data-bind="value:$root.initial" id="student.initial" name="student.initial"/>
<input type="text" data-bind="value:$root.dob" id="dob" name="dob" />
<button data-bind="click:save">Save</button>
}

<script type="text/javascript">
ko.applyBindings(new records.models.students_model());
</script>

我在这里做错了什么?我在这里知道这个问题:Pass a function that returns the value of the ko.computed但似乎那个人有不同的问题。在 save 方法中启动时我的代码失败。具体行:

data:ko.toJSON(form[0])

最佳答案

ko.toJSON 期望您将您的 viewModel 传递给它,但您传递给它的是来自 DOM 的元素,因此出现错误。

您需要将 javascript 对象( View 模型或 View 模型的一部分)传递给 ko.toJSON。例如,如果你想发送学生数组,你可以这样做:

ko.toJSON(self.students);

我看到您的表单有一些输入绑定(bind)到 $root.fname$root.lname$root.initial$root.dob,但我不确定它们在您的 View 模型中的什么位置,所以我无法准确告诉您要传递的内容。但我可以举一个例子说明可以解决这个问题的方法。

如果你有一个看起来像这样的 View 模型:

var data = ...;
var vm = {
newStudent : {
fname : ko.observable(data.fname),
lname: ko.observable(data.lname),
initial: ko.observable(data.initial ?? ""),
dob: ko.observable(data.dob)
}
}

然后您通过调用将其绑定(bind)到您的 dom

ko.applyBindings(vm);

然后您可以像这样调用 ko.toJSON:

...
data:ko.toJSON(vm.newStudent),
...

关于javascript - 传递一个函数,该函数在提交期间返回 ko.computed 错误的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16115790/

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