Handelbarsを使用した私のbackbone.jsアプリケーションでは、以下のことが行われます。Handlebars.jsを使用したBackbone.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 [0]の代わりに "js"だけを実行すると、JSONオブジェクトには大括弧と末尾の角括弧が付きます。したがって、JSONオブジェクトの配列オブジェクトとして認識されます。だから私はjs [0]にしなければならなかった。しかし、私はそれが適切な解決策ではないように感じます。
「ビュー」を初めて作成するときは、次のように作成しています。
ws._index = new ArticleListView({model:ws._articles});
しかし、私の場合、私は
ws._index = new ArticleListView({collection: ws._articles});
Iない万一すればよいですか? (私はチュートリアルbtwに従っていた)。それともこの問題?私は両方を試みましたが、それほど大きな違いはありませんでした。
ありがとうございます。
このhandlebar.jsテンプレートを自分のhtmlの – Vinodh