HandleBars.jsを使用したbackbone.jsに関する質問
-
27-10-2019 - |
質問
Handelbarsを備えた私の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>
上記のコードは正常に機能し、記事のタイトルを印刷します。しかし、私の質問はそうです
Contextを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});
私はすべきではありませんか? (私はチュートリアルのところに従っていました)。それともこれは重要ですか?私は両方を試しましたが、それはあまり違いを生むようには見えませんでした。
前もって感謝します。
解決
あなたはコレクションのビューを作成しているようですので したほうがいい 使用してビューを初期化します 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;
}
});
そして、テンプレートにこのようなものを使用します
{{#each articles}}
{{this.title}}
{{/each}}
PSラインJSON.parse(JSON.stringify(this.model.toJSON()))
に相当します this.model.toJSON()
お役に立てれば
他のヒント
var ArticleListView = Backbone.View.extend({
initialize: function(){
this.template = Handlebars.compile($('#articles_hb').html());
},
render: function(){
$(this.el).html(this.template(this.model.toJSON()));
return this;
}
});
/////////////////////////////////////
ws._index = new ArticleListView({model: ws._articles});