javascript 敲除模板 - 将文本绑定到函数,并传入模板数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16531012/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 05:02:00  来源:igfitidea点击:

knockout template - binding text to a function, with template data passed in

javascriptjqueryknockout.jsunderscore.js

提问by nuway

i have a view model with an observable array. Its populated with some json:

我有一个带有可观察数组的视图模型。它填充了一些json:

this.socialTiles = ko.observableArray([]);

ko.computed(function () {

  jQuery.getJSON( this.apiURL+"&callback=?", function (data) {

    var theData = data.entries; 
    tilesModel.socialTiles(theData);
    console.dir(theData);
  });
}, tilesModel);

for each item in the model, i build an li using template:

对于模型中的每个项目,我使用模板构建一个 li:

<ul id="tiles-ul" data-bind="template: {name:'twitter_template', foreach:socialTiles}">



<script type="text/html" id="twitter_template"> 
  <li class="social-tile box-shadow">
    <div class="header">
      <div class="header-img">
        <img data-bind="attr: { src: actor.avatar}">
      </div>
      <div class="name_and_time">
        <span class="full-name" data-bind="text: actor.title"></span>
        <span class="twitter-name" data-bind="text: actor.id"></span>
        <span class="how-long-ago" > 5 minutes ago </span>
      </div>
    </div>
    <div class="message-content" data-bind="html: object.content">
    </div>
    <div class="footer">
      <div class="social-icon-twitter">
      </div>
    </div>  

    <span data-bind="text: $index"></span>      
  </li>   
</script>

id like to data-bind the text of an element to be a result of a function, with the current data from the model used as an argument . example:

id 喜欢将元素的文本数据绑定为函数的结果,并将模型中的当前数据用作参数。例子:

actor.id is a string containing a twitter url of a user (like "http://twitter.com/iamdiddy")

actor.id 是一个包含用户 twitter url 的字符串(如“ http://twitter.com/iamdiddy”)

i'd like to pass that string to a function and return a "#iamdiddy" representation.

我想将该字符串传递给一个函数并返回一个“#iamdiddy”表示。

<span class="twitter-name" data-bind="text: getTwitterTag(actor.id)"></span>

in the view model

在视图模型中

 function getTwitterTag("twURL"){
    return ... whatever;
}

how can I do this (call a function with argument, not extract the #... )? Does knockout support this functionality?

我该怎么做(调用带参数的函数,而不是提取 #... )?淘汰赛是否支持此功能?

回答by RodneyTrotter

Try changing

尝试改变

<span class="twitter-name" data-bind="text: getTwitterTag(actor.id)"></span>

to

<span class="twitter-name" data-bind="text: $root.getTwitterTag($data)"></span>