knockout.viewmodel icon indicating copy to clipboard operation
knockout.viewmodel copied to clipboard

Stuck with Dynamic Properties

Open emansouri opened this issue 11 years ago • 3 comments

I have an issue that may be more a general knockout issue but I am using the viewmodel plug-in.

I'll simplify my current use case as much as possible.

I have an object, obj, which has a number of properties, each of which are arrays, for instance:

var obj = {}; obj[1] = [{id:1},{id:2}]; obj[5] = [{id:3},{id:4}]; obj[10] = [{id:5},{id:6}];

var provider = { obj:obj};

I create a view model:

var vm = ko.viewmodel.fromModel(provider);

I am then able to bind to existing properties on the view, for example:

<span data-bind="text: provider.obj[5][0].id()"></span>

My question is how can I attach a new array to provider.obj such that it will have the pushFromModel() method available:

I have tried:

var new_array = ko.observableArray(); vm.provider.obj[20] = new_array;

and a number of other things.

Basically, I am stuck on how to add new properties to an existing observable object.

emansouri avatar Jan 22 '14 12:01 emansouri

After looking at the docs, it seems that pushFromModel is something added to the observableArray during the transformation process. It's not something that is normally part of an observableArray. According to the docs, under the covers it applies the original mapping options and then calls push. So, if you don't have any mapping you need to perform on the new object, then you should be able to just call push instead.

If you do need to perform some mapping, then you might be able to make it work by copying an existing version of pushFromModel onto your new array. You could do something like this:

var new_array = ko.observableArray();
new_array.pushFromModel = provider.obj[1].pushFromModel;
vm.provider.obj[20] = new_array;

EisenbergEffect avatar Jan 22 '14 15:01 EisenbergEffect

This is very helpful! Your strategy to copy the pushFromModel to new observable array instances and then to assign them to the object worked great.

emansouri avatar Jan 22 '14 16:01 emansouri

@emansouri You have a couple of open tickets which aren't really issues, rather you seeking help. It would be good if you could close them. :)

kwakwaversal avatar Mar 11 '14 08:03 kwakwaversal