jsFiddle example
I have an observableArray
of selectable items (in a table). What I'm trying to do is open a modal on click of the table row, populate the modal with the item details, allow editing of the item and then save the changes - reflecting the updated item in the observableArray
. I've got everything else working so far, but can't seem to get the array item to update.
So far I've tried:
- Making every item in the
observableArray
anobservable
- using
.replace
on the array to update the item - this does work, but it just feels wrong - posting back the updated item, applying it to the database and rebinding the array - although this works, doesn't this defeat the point of KnockoutJS?
I've provided a jsFiddle link above that demonstrates what I'm trying to achieve.
View model and initialization
Feel free to make any suggestions on how I'm initializing self.selectItem
I'm currently in the learning stage of KnockoutJS, and doing so by playing around with mock projects so I'm open to all constructive criticism.
var items = [{
Id: 1,
Text: 'First item'
}, {
Id: 2,
Text: 'Second item'
}];
var viewModel = function (items) {
var self = this;
self.items = ko.observableArray(items);
self.selectedItemId = ko.observable();
self.item = ko.observable();
self.selectItem = function (item) {
for (var i = 0; i < self.items().length; i++) {
if (self.items()[i].Id === self.selectedItemId()) {
self.item(self.items()[i]);
break;
}
}
};
};
ko.applyBindings(new viewModel(items));
Markup bindings
<select data-bind="options: items, optionsCaption: 'Select...', optionsText: 'Text', optionsValue: 'Id', value: selectedItemId, event: { change: selectItem }"></select>
<div data-bind="if: item">
<input type="text" data-bind="value: item().Text" />
</div>
<table>
<thead>
<tr>
<th>Text</th>
</tr>
</thead>
<tbody data-bind="foreach: items">
<tr>
<td data-bind="text: $data.Text"></td>
</tr>
</tbody>
</table>