【发布时间】:2014-04-29 12:30:42
【问题描述】:
这是我的主干代码,我在其中使用下划线模板,现在工作正常,我正在尝试将该模板设为外部并从那里加载
这是我的示例主干代码
骨干应用
<div class="list"></div>
<script id="personTemplate" type="text/template">
<strong><%= name %></strong> (<%= age %>) - <%= occupation %>
</script>
<script type="text/javascript">
var Person = Backbone.Model.extend({
defaults: {
name: 'Guest User',
age: 23,
occupation: 'worker'
}
});
var PersonView = Backbone.View.extend({
tagName: 'li',
template: _.template( $('#personTemplate').html()),
initialize: function(){
this.render();
},
render: function(){
this.$el.html( this.template(this.model.toJSON()));
}
});
var person = new Person; // a person object created...
//person.set('name', 'abhi');
var personView = new PersonView({ model: person });
personView.el // ---->; You can call this method and it will display the view..
$(document.body).html(personView.el);
</script>
</body>
</html>
真正需要的是我将这个模板<strong><%= name %></strong> (<%= age %>) - <%= occupation %> 放在一个外部文件中。我不太了解它的扩展名,我认为它可以是一个 html 文件并从那里加载模板,我对其进行了研究并找到了一些示例代码并尝试了类似的东西
<script type="text/javascript">
_.mixin({templateFromUrl: function (url, data, settings) {
var templateHtml = "";
this.cache = this.cache || {};
if (this.cache[url]) {
templateHtml = this.cache[url];
alert(templateHtml);
} else {
$.ajax({
url: url,
method: "GET",
async: false,
success: function(data) {
templateHtml = data;
alert(templateHtml);
}
});
this.cache[url] = templateHtml;
}
return _.template(templateHtml, data, settings);
}});
var Person = Backbone.Model.extend({
defaults: {
name: 'Guest User',
age: 23,
occupation: 'worker'
}
});
var PersonView = Backbone.View.extend({
tagName: 'li',
template:_.templateFromUrl("templatefile1.html", {"name": "value","age":10}) ,
// template:_.templateFromUrl("templatefile1.html", this.model.toJSON()) ,
//template: _.template( $('#personTemplate').html()),
initialize: function(){
this.render();
},
render: function(){
alert(this.template);
this.$el.html( this.template);
}
});
var person = new Person; // a person object created...
//person.set('name', 'abhi');
var personView = new PersonView({ model: person });
personView.el // ---->; You can call this method and it will display the view..
$(document.body).html(personView.el);
</script>
但是当我像这样调用模板时template:_.templateFromUrl("templatefile1.html", {"name": "value","age":10}) ,
这是工作
但是当我尝试像这样将传递模型传递给该模板时
template:_.templateFromUrl("templatefile1.html", this.model.toJSON())
我遇到了像
这样的异常Uncaught TypeError: Cannot read property 'toJSON' of undefined
我该如何解决这个问题
【问题讨论】:
-
小心
$(document.body).html(personView.el);,看起来您将<script>s 存储在<body>中,而$('body').html(...)在添加新内容之前会清除<body>。 -
@mu 太短了 1 感谢您的想法,这只是一个示例代码
-
@mu 太短了,我试过了,但是还是不行,能否提供代码?
-
您具体尝试了什么?具体出了什么问题?
标签: javascript templates backbone.js underscore.js