【发布时间】:2011-09-08 08:08:02
【问题描述】:
我的带有 Handelbars 的主干.js 应用程序执行以下操作。
- 设置模型、它的集合、视图和路由器。
- 一开始,从服务器获取文章列表并通过 Handlebars.js 模板使用视图呈现它。
代码如下。
(function ($)
{
// model for each article
var Article = Backbone.Model.extend({});
// collection for articles
var ArticleCollection = Backbone.Collection.extend({
model: Article
});
// view for listing articles
var ArticleListView = Backbone.View.extend({
el: $('#main'),
render: function(){
var js = JSON.parse(JSON.stringify(this.model.toJSON()));
var template = Handlebars.compile($("#articles_hb").html());
$(this.el).html(template(js[0]));
return this;
}
});
// main app
var ArticleApp = Backbone.Router.extend({
_index: null,
_articles: null,
// setup routes
routes: {
"" : "index"
},
index: function() {
this._index.render();
},
initialize: function() {
var ws = this;
if( this._index == null ) {
$.get('blogs/articles', function(data) {
var rep_data = JSON.parse(data);
ws._articles = new ArticleCollection(rep_data);
ws._index = new ArticleListView({model: ws._articles});
Backbone.history.loadUrl();
});
return this;
}
return this;
}
});
articleApp = new ArticleApp();
})(jQuery);
Handlebars.js 模板是
<script id="articles_hb" type="text/x-handlebars-template">
{{#articles}}
{{title}}
{{/articles}}
</script>
上面的代码工作正常,它打印文章标题。但是,我的问题是
将上下文传递给 Handlebars.js 模板时,我目前正在执行
$(this.el).html(template(js[0]))。这是正确的方法吗?当我只做“js”而不是 js[0] 时,JSON 对象有前导和结束的方括号。因此它被识别为 JSON 对象的数组对象。所以我不得不js [0]。但我觉得这不是一个合适的解决方案。-
当我第一次创建“视图”时,我正在创建它,如下所示。
ws._index = new ArticleListView({model: ws._articles});
但就我而言,我应该这样做
ws._index = new ArticleListView({collection: ws._articles});
我不应该吗? (顺便说一句,我正在学习教程)。或者这有关系吗?两个都试了,好像没什么区别。
提前致谢。
【问题讨论】:
-
如何将这个 handlebar.js 模板包含到我的 html 中
标签: javascript backbone.js handlebars.js