javascript 使用主干调用下划线模板内的函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18961438/
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
Call a function inside an underscore template using backbone
提问by Vic
Just a thing I try to do that would really simplify my life right now.
只是我尝试做的一件事会真正简化我现在的生活。
How can I do that :
我怎样才能做到这一点 :
This is my view in app file
这是我在应用程序文件中的视图
window.ArtView = Backbone.View.extend({
template:_.template($('#art').html()),
render:function (eventName) {
var output="blablbla";
$(this.el).html(this.template({"output":output}));
return this;
}
});
...
// function that I would like to call
function callFunction(){
console.log('it works!');
}
Template in index.html
index.html 中的模板
<script type="text/tempate" id="art">
<div data-role="header" class="header" data-position="fixed">
<a href="#" data-icon="back" class="back ui-btn-left">Back</a>
</div>
<div data-role="content" class="content">
callFunction();
<% console.log(output) %>
</div>
</script>
How can I call callFunction() inside my template or something alike ?
我如何在我的模板或类似的东西中调用 callFunction() ?
Any idea ?
任何的想法 ?
Thanks !
谢谢 !
回答by Vic
I believe you can call functions within the template as long as the object for the template has the function.
我相信只要模板的对象具有该函数,您就可以在模板内调用函数。
render:function (eventName) {
var output="blablbla";
var data = _.extend({"output":output}, callFunction);
$(this.el).html(this.template(data));
return this;
}
then in your template:
然后在您的模板中:
<%= callFunction() %>
回答by Yazan Rawashdeh
this is how I did it , it works fine.
我就是这样做的,效果很好。
template: _.template(templateText , {
imports : {
check :function (val){
// blah blah
}
}
}
}),
then in your html template
然后在你的 html 模板中
<%= check('value') %>
回答by Krasimir
That's wrong. Think about the template as a string, html markup. You get it and replace some parts of it with the actual data. If you want to do some DOM manipulation they should be made after that. Let us know what you want to do in callFunction and we may guide you to the right place for that logic.
那是错误的。将模板视为字符串、html 标记。你得到它并用实际数据替换它的某些部分。如果您想做一些 DOM 操作,则应在此之后进行。让我们知道您想在 callFunction 中做什么,我们可能会引导您到该逻辑的正确位置。