Search code examples
javascriptknockout.jsknockout-2.0knockout-3.0

knockoutjs image src not getting updated from ko.observable


I have this code:

  <tr data-bind="foreach: ProductEffectImagesToMatch()">
                            <td>
                                <span>
                                    <img data-bind="attr: { src: PoseId() ? ImageSrc() : '../images/style2/pose-select-placeholder.png' }, click: $root.PasteSpring"
                                        width="120" />
                                </span>
                            </td>
                        </tr>

I'm setting the ImageSrc in the code, but I'm not sure if I need to call something additionally to apply the bindings because although the value is set, I can see that in console.log the image url is not getting updated.

This is the viewmodel:

function EffectSelectionRootModel(imagesrc, poseid) {
        var self = this;
        self.ImageSrc = ko.observable();;
        self.PoseId = ko.observable();

        if (imagesrc) {
            self.ImageSrc(imagesrc);
        }

        if (poseid) {
            self.PoseId(poseid);
        }
    }

And this is how the values are set:

var itemToEdit = ko.utils.arrayFirst(self.ProductEffectImagesToMatch(), function (item) {
                return item;
            });

            if (itemToEdit) {
                itemToEdit.ImageSrc = self.selectedPose().ImageUrl;
                itemToEdit.PoseId = self.selectedPose().Id;
            }

And the viewmodel after the execution of that code:

enter image description here

But the image is not updated on the page.

Any idea what else I need to do?


Solution

  • Do it like this

    var itemToEdit = ko.utils.arrayFirst(self.ProductEffectImagesToMatch(), function (item) {
                return item;
            });
    
            if (itemToEdit) {
                itemToEdit.ImageSrc(self.selectedPose().ImageUrl);
                itemToEdit.PoseId(self.selectedPose().Id);
            }
    

    You have to set new values this way, if not you are overwriting the observable and it will no longer work.