Reputation: 167
I have an observable collection of the culture specific objects. There is a requirement to edit/display invariant item separately from the main edit screen.
The question is - can I make two way binding to a single item in the collection.
A simplified version of the much more complex UI/Viemodel is available at this fiddle:
I tried computed writable property in my view model, but it does not detect when invariant item is changed in the collection
Your input will be greatly appreciated. The code is listed bellow:
var ItemDescription = function () {
var me = this;
me.CultureInvariantId = ko.observable(0);
me.CultureFormat = ko.observable('');
me.Description = ko.observable('');
me.IsInvariant = ko.observable(false);
};
function viewModel()
{
var me = this;
me.Name = ko.observableArray();
me.InvariantName = ko.observable('');
}
function Initialize()
{
var model = new viewModel();
var invItemDescription = new ItemDescription();
invItemDescription.Description('Invariant description');
invItemDescription.CultureFormat ('');
invItemDescription.IsInvariant = true;
model.Name.push(invItemDescription);
var usItemDescription = new ItemDescription();
usItemDescription.Description('USA description');
usItemDescription.CultureFormat ('en-US');
usItemDescription.IsInvariant = false;
model.Name.push(usItemDescription);
return model;
}
ko.applyBindings(new Initialize());
Upvotes: 2
Views: 553
Reputation: 114792
If I understand what you are trying to do, then I think that a decent option would be to create a computed observable that represents the invariant ItemDescription
object. Then, you can use the with
binding to bind an editor against its properties.
Something like:
function viewModel()
{
var me = this;
me.Name = ko.observableArray();
me.SelectedName = ko.observable();
me.InvariantName = ko.computed(function() {
return ko.utils.arrayFirst(me.Name(), function(name) {
return name.IsInvariant;
});
});
}
With markup like:
<select data-bind="options: Name, optionsText: 'Description', value: SelectedName">
</select>
<div data-bind="with: SelectedName">
<textarea data-bind="value: Description"> </textarea>
</div>
Edit Invariant:
<div data-bind="with: InvariantName">
<input type="input" data-bind="value: Description" />
</div>
Sample: http://jsfiddle.net/rniemeyer/3cH8T/
Upvotes: 1