Search code examples
javascriptknockout.jsknockout-2.0knockout-3.0

knockoutjs data-bind dynamically img src based on index


I have this code:

  <tbody>
                        <tr data-bind="foreach: EffectQuantityTotal">
                            <td>
                                <span>
                                    <img data-bind="attr: { src: $root.ProductEffectImages() ? $root.ProductEffectImages()[0].ImageSrc : '../images/style2/pose-select-placeholder.png' }, click: $root.Paste"
                                        width="120" />
                                </span>
                            </td>
                        </tr>
                    </tbody>

$root.ProductEffectImages() will be null until the actual click event 'Paste' will not be done. The placeholder image is displayed fine but I want to update the image once the click function is completed. The object gets created correctly, but I want to get the nth imageurl for each effectquantitytotal, so for example if I have EffectQuantityTotal of 3, for each value I'll create image placeholder and before selecting the ImageUrl the placeholder will be shown but once the image is selected the proper image url will need to be set.

So instead of as I have for testing hardcoded now $root.ProductEffectImages()[0].ImageSrc the 0 will be replaced with nth value, probably by using $index instead of 0.


Solution

  • An observableArray initializes with an empty array, and not null, even if you pass it null. After you create it, you can assign it null and it will really have that value then, and your conditional will allow you to use

    src: $root.ProductEffectImages() ? $root.ProductEffectImages()[$index() - 1].ImageSrc : ...