eri*_*bae 7 javascript backbone.js handlebars.js
我与Handelbars的backbone.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);
Run Code Online (Sandbox Code Playgroud)
Handlebars.js模板是
<script id="articles_hb" type="text/x-handlebars-template">
{{#articles}}
{{title}}
{{/articles}}
</script>
Run Code Online (Sandbox Code Playgroud)
上面的代码工作正常,它打印文章标题.但是,我的问题是
将上下文传递给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});
Run Code Online (Sandbox Code Playgroud)
不应该吗?(我正在学习btw的教程).或者这有关系吗?我试过了两个,但似乎并没有太大的区别.
提前致谢.
tim*_*ham 24
您似乎正在为集合创建视图,因此您应该使用collection而不是使用初始化视图model.
至于把手,我没有经常使用它,但我想你想做这样的事情:
var ArticleListView = Backbone.View.extend({
el: $('#main'),
render: function(){
var js = this.collection.toJSON();
var template = Handlebars.compile($("#articles_hb").html());
$(this.el).html(template({articles: js}));
return this;
}
});
Run Code Online (Sandbox Code Playgroud)
然后使用类似的东西作为模板
{{#each articles}}
{{this.title}}
{{/each}}
Run Code Online (Sandbox Code Playgroud)
ps这条线
JSON.parse(JSON.stringify(this.model.toJSON()))相当于this.model.toJSON()
希望这可以帮助
| 归档时间: |
|
| 查看次数: |
14712 次 |
| 最近记录: |