I have the following object.
var q = {
availableModels: ko.observableArray();
selectedModel: ko.observable();
displayModel: function(item) { return item.text; }
image: ko.computed(function() {
return q.selectedModel().image;
});
}
Which is bound to the following element.
<select data-bind="options: availableModels, value: selectedModel, optionsText: displayModel, optionsCaption: 'Choose a Model'"></select>
And an image.
<img data-bind="attr: { src: image }">
I push some objects into availableModels.
q.availableModels.push({ index: 0, text: 'castis0', image: 'castis0.jpg'});
q.availableModels.push({ index: 1, text: 'castis1', image: 'castis1.jpg'});
I then set the selectedModel
q.selectedModel({ index: 1, text: 'castis2', image: 'castis2.jpg' });
The html element does contain the objects that I’ve pushed into availableModels but the currently selected element is not changed by setting selectedModel.
It does work if I apply the change as such.
q.selectedModel = ko.computed(function() {
for(var i = 0; i < q.availableModels().length; i++) {
var data = q.availableModels()[i];
if (data.index == 1) {
return data;
}
}
})
But the image’s src is not changed.
I’m un aware of what I need to change,
What happens here is that you are not dealing with references to the same object. Here is a sample:
So, in your case, you would need to set the selectedModel equal to the actual object from your array like:
There are a few issues with the way that your view model is defined as well. If you are defining it as an object literal, then you need to place a comma between each property. Also, the computed observable tries to evaluate itself immediately, and it can’t access the properties of that object literal until after it is closed.
Here is an updated sample with a few changes: http://jsfiddle.net/rniemeyer/sq263/