在 KNOCKOUT.js 中动态调用 attr src 上的子级函数

Dynamically call a function on child on attr src in knockout.js

本文关键字:函数 src attr js KNOCKOUT 动态 调用      更新时间:2023-09-26

我正在尝试在attr src上调用一个函数,但失败了。这是我尝试过的。

function FavoriteViewModel() {
    var self = this
    self.FavoriteProfiles   =   ko.observableArray([])
    self.getRating  =   function(Rating){
        //here i want conditions and concat image path
        return does nothing here
    }
    self.LoadData   =   function(){
        //run ajax and put its result in self.FavoriteProfiles
        self.FavoriteProfiles(Result)
    }   
    self.LoadData()
}

当我运行 ajax 时,这会带来这个结果。结果是多个我只发布单个对象来理解

ProfileId   20
Age         21
Gender      "F"
Rating      4

我像这样绑定数据

<div id="favorite-related-profiles" data-bind="foreach:FavoriteProfiles">
<article class="prfl_box">
    <p>
        <span id="favorite-related-age" data-bind="text:Age"></span>               
        <span id="favorite-related-gender" data-bind="text:Gender"></span>               
        <br>
        <img id="favorite-related-rating" class="pro_rating" src="" data-bind="attr:{src:Rating}">
    </p>
</article>
</div>

当我像这样尝试这种绑定时

<img id="favorite-related-rating" class="pro_rating" src="" data-bind="attr:{src:$root.getRating.bind($data,Rating)}">

我在 src 中得到这个

src="function () { [native code] }"

如何动态生成 src 属性。
注意我需要显示图像。图像被命名为 4rating.png 、5rating.png 、default.png。我想检查 src 属性中的评级是否为 4 ass 4rating。我该怎么做。

好的,有几种方法可以做到这一点。现在,如果我理解了您的问题,那么您需要将 src 属性作为 4rating.png5rating.png 等,具体取决于评级值分别为 4,5。

如果这是场景,请查看此演示 - 一种肮脏的方式

现在,让我们让它按照您的代码运行:-

你可以看看 DEMO2- 正确的方式。如果您检查元素并看到 yopu 会找到如下 HTML 标记:-

<td data-bind="attr:{src: $root.getRating($data)}" src="4rating.png">
            </td>

希望对您有所帮助。

编辑:-

只是一个建议,当您使用挖空模型时,您可以保持模型独立。保持流程简单,它将更具可扩展性。我将分享如何使用揭示模块模式演示来学习敲除编码。

创建视图模型,如下所示:-

function FavoriteViewModel(data) {
    var self = this
    self.ProfileId = data.ProfileId;//Do some exception handling
    self.Age = data.Age;//Do some exception handling
    self.Gender = data.Gender;//Do some exception handling
    self.Rating = data.Rating;//Do some exception handling
    self.RatingExtended = data.Rating + "rating.png"; //Some random stuff
}

创建一个变量,该变量将保存您的收藏夹数组并将data-bind为 HTML。

var FavoriteProfiles = ko.observableArray([]);

最后,AJAX 调用以获取数据并将其分配给您的FavoriteProfiles

var ajaxdata = DummyAjaxCall(); //get all profiles
        $.each(ajaxdata, function (index, value) {
            FavoriteProfiles.push(new FavoriteViewModel(value)); //Create a Model
        });

将数据绑定更改为:

data-bind="attr:{src:$root.getRating.bind($data,Rating)}"

所有改变的是我从函数调用周围获取了'',因为通过这样做,您实际上是将函数的 src 设置为字符串。

编辑:尝试删除函数上的绑定

data-bind="attr:{src:$root.getRating($data,Rating)}"