use*_*258 6 javascript templates function backbone.js underscore.js
我试图在Underscore模板中使用一个函数,如下所示,但我收到一个错误:
未捕获的ReferenceError:未定义getProperty
以下是我正在使用的代码
var CustomerDetailView = Backbone.View.extend({
tagName : "div",
template: "#customer-detail-view-template",
initialize: function() {
_.bindAll(this, 'render');
this.model.bind('change', this.render);
this.initializeTemplate();
},
initializeTemplate: function() {
this.template = _.template($(this.template).html());
},
render: function() {
var data = this.model.toJSON();
_.extend(data, viewHelper);
console.log(data);
var html = _.template($(this.template), data);
$(this.el).html(html);
return this;
}
})
Run Code Online (Sandbox Code Playgroud)
和模板:
<script type="text/template" id="customer-detail-view-template">
<div style="height: 70px;">
<span class="displayText">
<p class="searchResultsAuxInfo">Full Name : <%= getProperty("full_name", null) %> </p>
<p class="searchResultsAuxInfo">Country Code : <%= getProperty("country_code", null) %></p>
<p class="searchResultsAuxInfo">street : <%= getProperty("street", null) %></p>
<p class="searchResultsAuxInfo">maiden_name : <%= getProperty("maiden_name", null) %></p>
</span>
<span class="displayTextRight">
<p class="searchResultsAuxInfo">marital_status_code : <%= getProperty("marital_status_code", null) %></p>
<p class="searchResultsAuxInfo">tax_id_number : <%= getProperty("tax_id_number", null) %></p>
<p class="searchResultsAuxInfo">primary_phone : <%= getProperty("primary_phone", null) %></p>
<p class="searchResultsAuxInfo">customer_number : <%= getProperty("customer_number", null) %></p>
</span>
</div>
</script>
Run Code Online (Sandbox Code Playgroud)
视图助手对象如下所示:
var viewHelper = {
getProperty:function(propertyName, object) {
if(typeof(object) === "undefined"){
object = this["attributes"];
}
for (i in object) {
if (_.isObject(object[i])) {
var currentObj = object[i];
if(_.has(currentObj, propertyName)){
return currentObj[propertyName];
}
this.getProperty(propertyName, currentObj);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
mu *_*ort 13
你的问题是,一旦你进入render,this.template:
var html = _.template($(this.template), data);
Run Code Online (Sandbox Code Playgroud)
已经是一个编译模板函数:
initializeTemplate: function() {
this.template = _.template($(this.template).html());
}
Run Code Online (Sandbox Code Playgroud)
该_.template呼叫:
将JavaScript模板编译为可以评估渲染的函数.
所以你这样说:
_.template($(some_compiled_template_function).html(), data);
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Run Code Online (Sandbox Code Playgroud)
那就是执行以下$(function() { ... })形式$():
绑定DOM完成加载时要执行的函数.
这一点点的混乱让一切都变得混乱和混乱.修复如何使用模板,事情将开始变得更有意义:
render: function() {
//...
var html = this.template(data);
//...
}
Run Code Online (Sandbox Code Playgroud)
你this.template将成为一个函数,render所以把它称为函数.
演示(为了清晰起见,有一些简化):http://jsfiddle.net/ambiguous/SgEzH/
| 归档时间: |
|
| 查看次数: |
12013 次 |
| 最近记录: |