Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Complex Object passed into ko.mapping.fromJS

I have a complex object I want to pass into ko.mapping.fromJS and my problem is that I only want one field to be observable, but the other properties come across as either null or non-existent based on the methods I have tried.

I have created a jsFiddle here to illustrate my problem. I wish for the inner object to simply be copied as I have no need for it to be observable; I don't want the extra overhead considering the number of these I will have.

The goal of this would be to make the qty editable, but the inner.name remain the same in the text box. This would mean that one is an observable while the other is not.

If any one has another way of doing it that does not involve the mapping I would love to hear it. My view model has quite a few functions and such, and the data is coming in from an AJAX call.

function viewModel() {
    var self = this;
    self.slots = ko.observableArray([]);

    self.load = function() {
        ko.mapping.fromJS(
            [
                { 'qty': 1, 'inner': { 'name': 'thing'} },
                { 'qty': 2, 'inner': { 'name': 'stuff'} }
            ],
            { 'include': ['qty'], 'ignore': ['inner.name'] },
            self.slots);
    }
};

ko.applyBindings(new viewModel());

<button data-bind="click: load">Go</button>
<ul data-bind="foreach: slots">
    <li>
        <span data-bind="text: qty"></span>&nbsp;<span data-bind="text: inner.name"></span><input data-bind="value: qty" /><input data-bind="value: inner.name" />
    </li>
</ul>
like image 535
PCasagrande Avatar asked Feb 28 '26 00:02

PCasagrande


1 Answers

You need to use copy instead of ignore because you want to have properties there just not be observable.

And because you are mapping directly an array the mapping configuration becomes a little bit complicated.

You cannot define copy on the "root" level because you have the array at the root. So you have to supply a create function for the items and in the create function you can now specify the copy options for the properties of the item:

   ko.mapping.fromJS(
        [
            { 'qty': 1, 'inner': { 'name': 'thing'} },
            { 'qty': 2, 'inner': { 'name': 'stuff'} }
        ],
        {
            create: function (options) {
                return ko.mapping.fromJS(options.data, {
                    copy: ['inner.name']
                })
            }
        },
        self.slots);

Demo JSFiddle.

like image 132
nemesv Avatar answered Mar 01 '26 14:03

nemesv



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!