Cannot map array to observableArray using ko.mapping

2,436 views
Skip to first unread message

Paul Cox

unread,
Feb 10, 2011, 1:17:57 PM2/10/11
to knock...@googlegroups.com
I'm currently using Knockout to create an editable grid for my MVC application. This worked well until I tried to add total fields like the Shopping Cart Example. I wanted the total to update when the value changed and realised I needed my observableArray to contain observable fields. Previously I had been using the JS array created by the server side code directly to create the observableArray.

However this code returns an empty array for the creditorModel using the knockout-1.1.2 and knockout.mapping-latest. Am I doing something silly here?

var creditorData = [{"DebtSolutionCreditorId":3,"AccountNumber":"123456","AmountOwed":1000,"LenderId":48,"NameOnAgreement":"test name","Repayment":200},{"DebtSolutionCreditorId":4,"AccountNumber":"123456","AmountOwed":6000,"LenderId":3,"NameOnAgreement":"test name","Repayment":200}]; 

var creditorModel = ko.mapping.fromJS(creditorData); 

Thanks,
Paul

rpn

unread,
Feb 10, 2011, 2:07:30 PM2/10/11
to KnockoutJS
Looks like you need your root object to not be an array.

More like:
var creditorData = { "creditors":
[{"DebtSolutionCreditorId":3,"AccountNumber":"123456","AmountOwed":
1000,"Le nderId":48,"NameOnAgreement":"test
name","Repayment":200},{"DebtSolutionCreditorId":
4,"AccountNumber":"123456" ,"AmountOwed":6000,"LenderId":
3,"NameOnAgreement":"test
name","Repayment":200}] };
var creditorModel = ko.mapping.fromJS(creditorData);

Hope this helps.

On Feb 10, 12:17 pm, Paul Cox <p...@houseofstraw.co.uk> wrote:
> I'm currently using Knockout to create an editable grid for my MVC
> application. This worked well until I tried to add total fields like the
> Shopping Cart Example. I wanted the total to update when the value changed
> and realised I needed my observableArray to contain observable fields.
> Previously I had been using the JS array created by the server side code
> directly to create the observableArray.
>
> However this code returns an empty array for the creditorModel using the
> knockout-1.1.2 and knockout.mapping-latest. Am I doing something silly here?
>
> var creditorData =
> [{"DebtSolutionCreditorId":3,"AccountNumber":"123456","AmountOwed":1000,"Le nderId":48,"NameOnAgreement":"test

Paul Cox

unread,
Feb 10, 2011, 2:25:42 PM2/10/11
to knock...@googlegroups.com
Thanks for the help. 

I did try something similar to that but then creditorModel.creditors is an empty array.

rpn

unread,
Feb 10, 2011, 3:36:06 PM2/10/11
to KnockoutJS
Hi Paul-
Maybe you can take a look at this: http://jsfiddle.net/rniemeyer/xxW4q/
and try to reconcile it with what you are doing to see if you can
demonstrate the problem.

Thanks.
Reply all
Reply to author
Forward
0 new messages