sencha / javascript - 如何从 tpl 模板内部调用函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6390845/
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
sencha / javascript - how to call a function from inside a tpl template
提问by mheavers
I'm using Sencha touch and I'm trying to modify a twitter example I found online in order to turn urls from a twitter feed into clickable links. I saw that one of the examples in the sencha touch library uses a linkify feature, but I can't figure out how to incorporate it into my own project. Here's my code:
我正在使用 Sencha touch,我正在尝试修改我在网上找到的一个 twitter 示例,以便将 twitter 提要中的 url 转换为可点击的链接。我看到sencha touch库中的一个例子使用了linkify功能,但我不知道如何将它合并到我自己的项目中。这是我的代码:
t_news = new Ext.Component({
cls:'t_news',
title:'News',
scroll: 'vertical',
tpl: [
'<tpl for=".">',
'<div class="tweet">',
'<div class="avatar"><img src="{profile_image_url}" /></div>',
'<div class="tweet-content">',
'<h2>{from_user}</h2>',
'<p>{text:this.linkify}</p>',
'</div>',
'</div>',
'</tpl>',
]
});
function linkify(value){
return value.replace(/(http:\/\/[^\s]*)/g, "<a target=\"_blank\" href=\"\"></a>");
}
and here's the error:
这是错误:
Uncaught TypeError: Object [object Object] has no method 'linkify'
回答by Stuart
If you declare your XTemplate explicitly you can use the last constructor parameter which accepts a configuration object where you can specify template functions. These functions can be called with the value:function syntax.
如果您明确声明您的 XTemplate,您可以使用最后一个构造函数参数,该参数接受一个配置对象,您可以在其中指定模板函数。可以使用 value:function 语法调用这些函数。
Your code will become:
您的代码将变为:
t_news = new Ext.Component({
cls:'t_news',
title:'News',
scroll: 'vertical',
tpl: new Ext.XTemplate(
'<tpl for=".">',
'<div class="tweet">',
'<div class="avatar"><img src="{profile_image_url}" /></div>',
'<div class="tweet-content">',
'<h2>{from_user}</h2>',
'<p>{text:this.linkify}</p>',
'</div>',
'</div>',
'</tpl>',
{
linkify: function(value){
return value.replace(/(http:\/\/[^\s]*)/g, "");
}
})
});
});
These functions are executed in the scope of the XTemplate and can also be called within tpl tags or in the square bracket notation:
这些函数在 XTemplate 的范围内执行,也可以在 tpl 标签或方括号中调用:
'<tpl if="this.linkify(values.text) == \'some text\'">',
'</tpl>'
'<p>{[this.linkify(values.text)]}</p>'
Hope this helps!
希望这可以帮助!
Cheers Stuart
干杯斯图尔特