javascript - Pass a function that returns the value of the ko.computed error during submit -
i'm having trouble submitting form knockout js.
i receive error "pass function returns value of ko.computed."
the code follows:
(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 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>
what doing wrong here? i'm aware of question here:pass function returns value of ko.computed seems individual had different problem. code fails when starting in save method. line:
data:ko.tojson(form[0])
ko.tojson
expecting pass viewmodel, you're passing element dom, error.
you need pass javascript object (a viewmodel or part of viewmodel) ko.tojson
. example, if wanted send array of students, this:
ko.tojson(self.students);
i see form has inputs bound $root.fname
, $root.lname
, $root.initial
, , $root.dob
, i'm not sure exist in viewmodel, can't tell pass. can give example of 1 way could solve this.
if have viewmodel looks this:
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) } }
and bound dom calling
ko.applybindings(vm);
you call ko.tojson
this:
... data:ko.tojson(vm.newstudent), ...
Comments
Post a Comment