0

I'm new to the mapping plugin and think that I'm missing something obvious.

How can I get ko.mapping to 'deeply' create members of observable arrays as observables themselves? I've looked at 'create callbacks' and 'options' in the documentation, but don't see anything obvious.

I have quite a large object model and so would prefer not to have to bind the viewModel by hand. Also, as a side issue perhaps, there is a need to add elements dynamically as observables as well.

html

<p>
    here, ko.mapping succesfully creates an observable...<br/>
    <input data-bind="value:someText, valueUpdate:'afterkeydown'"></input>
</p>

<p>
    however, here, the contents of the observable array are not observables...</br>    
    <span data-bind="foreach: { data: years, as: 'year' }">

   <input data-bind="value:year, valueUpdate:'afterkeydown'"></input>

    <br />
    </span>
    <button data-bind="click:function(){addYear();}">add</button>
</p>

<p><br /><br /><div data-bind="text: ko.toJSON($root)"></div></p>

javascript

var model={    
    someText: 'Hello',        
    years:[2000,2001,2002]
};

var viewModel = ko.mapping.fromJS(model);
viewModel.addYear=function(){viewModel.years.push(ko.observable(""));}
ko.applyBindings(viewModel);

Here's a jsFiddle link

Thanks very much for your help,

DS

1 Answer 1

3

I had to change your array to be an array of properties instead of just numbers. If you have just an array numbers, the mapping plugin doesn't covert them to observables.

var model={    
    someText: 'Hello',        
    years:[{item:2000},{item:2001},{item:2002}]
    };

See the Updated Fiddle

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.