Make multidimensional array observable

1,380 views
Skip to first unread message

Павел Шум

unread,
May 27, 2012, 7:37:03 AM5/27/12
to KnockoutJS
HI there.

I am building one application on Knockout and find it very useful.
Although, I have a problem with getting multidimensional array
(object) observable.

At the moment I am using following structure:
self.form = ko.observableArray(ko.utils.arrayMap(initialData,
function(section) {
var result = {
name : section.name,
code : section.code,
type : section.type,
fields: ko.observableArray(section.fields)
};
return result;
}));

It works well, but I can't get it working if the initialData is more
than two levels.
I tried something like
self.form = ko.observableArray(ko.utils.arrayMap(initialData,
function(block) {
var result = {
name : block.name,
code : block.code,
type : block.type,
sections:
ko.observableArray(ko.utils.arrayMap(block.sections, function(section)
{
var result = {
name : section.name,
code : section.code,
type : section.type,
fields: ko.observableArray(section.fields)
};
return result;
}))
};
return result;
}));

The final array structure looks good, but knockout doesn't updates DOM
when I am doing push to sections array:

self.addField = function( section ) {
field = {
code: uid(),
name: "New Field",
value: '',
type: section.type
};
section.fields.push(field);
};

I also tried a knockout.mapping.js plugin (is that a right approach?)
looks good first, but after a push in the function above I have my new
field element not observable, just object.

The plugin doumentation says:
// Every time data is received from the server:
ko.mapping.fromJS(data, viewModel);

But I am not sure that it is my case.


If anyone has any ideas, it would be much appreciated.
Thanks.

Павел Шум

unread,
May 27, 2012, 8:40:51 AM5/27/12
to KnockoutJS
Reply all
Reply to author
Forward
0 new messages