0

I would like to create a knockout custom binding (so I can add a computed observable) as with this example:

var mapping = {
    'children': {
        create: function(options) {
            return new myChildModel(options.data);
        }
    }
}

The problem is, my viewModel is the actual array (the root). Not a child property as 'children' in this example. So I need something like:

var mapping = {
    'root': {
        create: function(options) {
            return new myChildModel(options.data);
        }
    }
}

How can I achieve that? Thank you.

Ashraf Fayad
  • 1,433
  • 4
  • 17
  • 31

1 Answers1

0

Can't you just use the normal mapping function of the plugin to do that?

var viewmodel = ko.observableArray([]);
ko.utils.arrayForEach(options.data, function(data) {
    viewmodel.push(new myChildModel(data));
}

Though I would personally not make your view model the array, but make the array a property on the view model, it gives you more flexibility if you want to add more properties in the future.

Paul Manzotti
  • 5,107
  • 21
  • 27
  • Thanks for responding paul. But I need to do it through the 'create' function of the ko.mapping plugin. – Ashraf Fayad Apr 23 '13 at 12:53
  • If you need to do it through the create property, then I'm fairly sure that you need to have a property on your view model. To be honest, I don't think that having a view model that is just an array makes a great deal of sense, there's usually more information that you want to display on a page than that. – Paul Manzotti Apr 23 '13 at 13:08