我在我的项目中使用主干js,在这里我渲染这样的视图---
var View1 = Backbone.View.extend({
el: "#container",
initialize: function (){
this.render();
},
render: function(){
var parent = this;
$.get('http://localhost:8080/pages/task.jsp').done(function (data){
parent.$el.html(data);
var view = new ViewTask1()
})
}
});
在task.jsp内部,我有一个模板,希望单独渲染。该文件看起来像这样,..
<ul class="list-group">
<li class="list-group-item">Dapibus ac facilisis in</li>
<li class="list-group-item list-group-item-primary">A simple primary list group item</li>
</ul>
<div id="abc"></div>
<script type="text/template" id="task-card-template">
<div class="card" style="width: 18rem;">
<img class="card-img-top" src="..." alt="Card image cap">
<div class="card-body">
<h5 class="card-title">Card title</h5>
<p class="card-text">Some quick example text.</p>
<a href="#" class="btn btn-primary">Go somewhere</a>
</div>
</div>
</script>
然后我将一些数据插入到集合中,将集合映射到模型,并尝试按以下方式呈现此模板:
//Create Task View
var TaskView = Backbone.View.extend({
initialize : function() {
this.render();
},
template: _.template($('#task-card-template').html()),
render: function() {
this.$el.html(this.template(this.model.attributes));
return this;
}
});
var ViewTask1 = Backbone.View.extend({
el : "#abc",
initialize : function() {
this.render();
},
render : function() {
this.$el.html('');
Tasks.each(function(model) {
var task = new TaskView({
model : model
});
this.$el.append(task.render().el);
}.bind(this));
return this;
},
});
但我收到错误消息,TypeError:无法读取未定义的属性'replace'在Function.h.template下划线js。起初,我认为也许在调用模板views(ViewTask)之前未加载jsp或未渲染View1,但是正如我已经检查过的那样,在JSP完全渲染之后就调用了它。我的问题是如何从视图内部加载模板?
您走在正确的轨道上……看来您是在页面加载时在TaskView
内定义模板函数,而ajax才有机会将所需的html添加到页面中。即使您没有在ajax完成之前创建TaskView
的任何instances,视图定义仍在尝试立即使用该html。
我认为您有两种可能的解决方案:(1)在initialize
或render
方法中定义模板函数,直到您拥有实例后,该函数才会执行。或者(2)将html放在页面上的某个位置(也许在一个隐藏的div中),以便可以立即将其获取。
解决方案(1)可能看起来像这样:
var TaskView = Backbone.View.extend({
initialize: function() {
this.render();
},
// no template method yet
render: function() {
// inside render method, define template method if not already defined
if (!this.template) {
this.template = _.template($('#task-card-template').html());
}
this.$el.html(this.template(this.model.attributes));
return this;
}
});