Binding Image src as Expression in Knockout

2019-05-28 12:40发布

Please bear with me, if you find this question so stupid. I am a beginner to knockout and trying to learn it.

I want to bind image source to an expression. The expression is responsible to generate a path and that path must be applied as the Source to the img.

<ul id='AllPatient' data-role='listview' data-inset='true' data-bind="foreach:Patients">
            @*<li><span data-bind="text: ko.toJSON($data)"></span></li>*@
            <li>
                <table class="Tabular">
                    <tr>
                        <td class="DataCell">
                            <a href="javascript:" id="pLocation" sortorder="none"><span data-bind="text:$data.UnitName">
                            </span></a>
                        </td>
                        <td class="DataCellImage">
                            <a href="javascript:" id="addPatient" sortorder="none" data-bind="click:$root.addPatient">
                                <img data-bind="attr:{src: $root.ImageSource}" src="~/Content/Images/MPL/PersonAdd.png" /></a>
                        </td>
                    </tr>
                </table>
            </li>
        </ul>

I am using following databinding ViewModel:

function PatientsModel(data)
{
    var self = this;

    self.Patients = ko.observableArray([]);

    self.Patients(data.Patients);
    self.ImageSource = function (model)
    {
        if (model.myPatient == true)
        {
            return PyxisLinkJS.RootURL + '/Content/Images/MPL/MyPatientGray.png';
        }
        else if (model.localPatient == true)
        {
            return PyxisLinkJS.RootURL + '/Content/Images/MPL/PersonAdd.png';
        }
        else
        {
            return PyxisLinkJS.RootURL + '/Content/Images/MPL/MyPatientGray.png';
        }
    }
}

This is what happening: It is trying to set function body of ImageSource as the src for the Image. Where as I want to trigger the method ImageSource and set the return value as the Src of the Image.

Regards, Sumeet

1条回答
相关推荐>>
2楼-- · 2019-05-28 13:18

It's returning the function instead of the string, call it AS a function

<img data-bind="attr:{src: $root.ImageSource() }" src="~/Content/Images/MPL/PersonAdd.png" />

Also, you can combine these two:

self.Patients = ko.observableArray([]);
self.Patients(data.Patients);

// Into this
self.Patients = ko.observableArray( data.Patients );
查看更多
登录 后发表回答