Using postJSON with entire view model

245 views
Skip to first unread message

MrTea

unread,
Oct 28, 2010, 12:36:56 PM10/28/10
to KnockoutJS
Hi,

This is a bit of a noob question ;-( but given a view model, how can
you jsonify the entire thing to send back to the server?

var productViewModel = {
PartNumber: ko.observable(initialData.PartNumber),
Name: ko.observable(initialData.Name),
ShortDescription:
ko.observable(initialData.ShortDescription),
FullDescription:
ko.observable(initialData.FullDescription),
AdminComment: ko.observable(initialData.AdminComment),
Published: ko.observable(initialData.Published),
SelectedCategories:
ko.observableArray(ko.utils.arrayMap(initialData.AvailableCategories,
mapCategory)),

save: function() {
ko.utils.postJson(location.href, { productForm:
this });
}
};

This doesn't work, do I need to unwrap each observable property in
turn?

Thanks in advance,
Jon

Steven Sanderson

unread,
Oct 28, 2010, 1:19:57 PM10/28/10
to knock...@googlegroups.com
Hi there

If you grab the latest build from Github at http://github.com/SteveSanderson/knockout/tree/master/build/output/, you can use the new toJS / toJSON helpers.

e.g., ko.utils.postJson(url, { productForm: ko.toJS(this) })
or $.post(url, { dataJson : ko.toJSON(myViewModel) }) or whatever the correct jQuery syntax is

The toJS / toJSON helpers clone the whole object graph, stripping out all the layers of observability to make a plain JS object / JSON string.

Pretty soon, ko.utils.postJson will be enhanced so internally, it calls the helper for you and does the same.

Regards
Steve

MrTea

unread,
Oct 28, 2010, 1:59:09 PM10/28/10
to KnockoutJS
Thanks Steve,

I'll take a look at the latest version.

On Oct 28, 6:19 pm, Steven Sanderson <ste...@stevensanderson.com>
wrote:
> Hi there
>
> If you grab the latest build from Github athttp://github.com/SteveSanderson/knockout/tree/master/build/output/, you can
> use the new toJS / toJSON helpers.
>
> e.g., ko.utils.postJson(url, { productForm: ko.toJS(this) })
> or $.post(url, { dataJson : ko.toJSON(myViewModel) }) or whatever the
> correct jQuery syntax is
>
> The toJS / toJSON helpers clone the whole object graph, stripping out all
> the layers of observability to make a plain JS object / JSON string.
>
> Pretty soon, ko.utils.postJson will be enhanced so internally, it calls the
> helper for you and does the same.
>
> Regards
> Steve
>
Reply all
Reply to author
Forward
0 new messages