【发布时间】:2013-11-26 12:06:51
【问题描述】:
我在显示外部模板时遇到了一些问题。到目前为止,我有 main.js 文件、index.html 文件、header_content.html 文件(带有一些简单的 html 代码)、header.js 视图文件和 tpl.js 文件。
我的 index.html 非常简单,看起来像这样:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Backbone project</title>
<meta charset="utf-8"/>
<link rel="stylesheet/less" type="text/css" href="css/style.less">
<link rel="stylesheet/less" type="text/css" href="css/admin.less">
<script data-main="js/config" src="js/libs/require.min.js"></script>
</head>
<body>
<div id="container"></div>
</body>
</html>
接下来是main.js文件:
require([
'jquery',
'lodash',
'backbone',
'utils/tpl',
'views/header'
],
function($, _, Backbone, HeaderMenuView, tpl) {
IndexView = Backbone.View.extend({
initialize: function(){
this.el.html(); // is this right?
}
});
var index_view = new IndexView({el:'#container'});
tpl.loadTemplates(['header'], function() {
window.app = new IndexView({el:'#container'});
Backbone.history.start();
});
});
然后我有 header.js 视图文件:
define(
['jquery', 'lodash', 'backbone', 'utils/tpl'],
function($, _, Backbone, tpl) {
var HeaderMenuView = Backbone.View.extend({
initialize: function() {
this.template = _.template(tpl.get('header_content'));
},
render: function(eventName) {
this.$el.html(this.template());
return this.el;
},
});
return HeaderMenuView;
});
作为最后一个文件,我有 tpl.js 文件,如下所示:
define(
['jquery', 'lodash', 'backbone'],
function($, _, Backbone) {
var tpl = {
templates: {},
loadTemplates: function(names, callback) {
var that = this;
var loadTemplate = function(index) {
var name = names[index];
console.log('Loading template: ' + name);
$.get('templates/' + name + '.html', function(data) {
that.templates[name] = data;
index++;
if (index < names.length) {
loadTemplate(index);
} else {
callback();
}
});
};
loadTemplate(0);
},
get: function(name) {
return this.templates[name];
}
};
return tpl;
});
当我运行它时,我得到几个脚本错误:-/ 我想要的只是要在#container Div 中显示的 header_content.html 模板。
我做错了什么?
【问题讨论】:
-
你遇到什么样的错误?
-
@YuruiRayZhang 嗯,我遇到了几个错误,我认为我的代码一般有问题。尤其是 main.js 文件似乎引起了最多的问题。我得到植根于requirejs的fexample“错误:脚本错误”,“错误:模块的加载超时:主干”,也植根于requirejs......,有时我得到“tpl未定义”等等......哇:-/
-
嗯...我对requirejs不太了解。但请确保您获得了正确的backbonejs 加载路径配置。另外,确保 underscore.js 在backbone.js 之前加载。
标签: javascript jquery html backbone.js requirejs