ko.toJSON Issues

535 views
Skip to first unread message

mr.brad....@gmail.com

unread,
Sep 5, 2012, 1:12:48 AM9/5/12
to knock...@googlegroups.com
I am attempting to use ko.toJSON to prep my data before I send it to the server and I am unable to get the data.

in HTML <pre data-bind="text: ko.toJSON($data, null, 2)"></pre>  works great! 

BUT in javascript ko.toJSON(viewModel) is returning undefined!  WHY?

Also if I use ko.toJS(viewModel) it works but I get all the function code.

Anyone have any ideas?

Benjamin Gudehus

unread,
Sep 5, 2012, 4:56:37 AM9/5/12
to knock...@googlegroups.com
Maybe your viewModel is a function?

> console.log(typeof(viewModel))
function

mr.brad....@gmail.com

unread,
Sep 5, 2012, 8:54:48 AM9/5/12
to knock...@googlegroups.com
Yes it is a function.   What are my options?  Do I have to recode it to a variable or is there a less painful way?

rpn

unread,
Sep 5, 2012, 9:13:06 AM9/5/12
to knock...@googlegroups.com, mr.brad....@gmail.com
Maybe you can share some of your code.  Otherwise, if you are using a constructor function and your function that does ko.toJSON is on the view model, then you can call ko.toJSON(this) or ko.toJSON(self) if you saved off the value of this.

like:

var ViewModel = function() {
   this.name = ko.observable("Bob");

   this.save = function() {
       alert(ko.toJSON(this));
   };
};

Benjamin Gudehus

unread,
Sep 5, 2012, 12:22:48 PM9/5/12
to knock...@googlegroups.com
The two options to define a view model is to use object notation or a constructor function.

// object notation.
var viewModel = {name: ko.observable("Bob")}
ko.applyBindings(viewModel)
console.log(ko.toJSON(viewModel))

// contructor function.
var ViewModel = function() {
    this.name = ko.observable("Bob")
}
var viewModel = new ViewModel()
ko.applyBindings(viewModel)
console.log(ko.toJSON(viewModel))

By convention variable names of constructor functions should be like class names in e.g. Java and C#, so everyone can see, that one has to use the new keyword.

I think you just mixed the constructor function with the instantiated object.

--Benjamin

mr.brad....@gmail.com

unread,
Sep 5, 2012, 9:14:52 PM9/5/12
to knock...@googlegroups.com
Thanks, I had blended a couple of examples and lost track of what I was doing, I will watch my notation use moving forward.

What fixed it was proper use of the constructor so I had a viewModel variable. 

Working well now, much appreciated!
Reply all
Reply to author
Forward
0 new messages