テンプレート用のrequire.js、AMD、およびハンドルバーを使用してバックボーンアプリケーションを構築しようとしています。これが私のインデックスビューのコードです。
define([
'jquery',
'underscore',
'backbone',
'handlebars',
'collection/questions',
'helpers'
], function($, _, Backbone, Handlebars, QuestionsCollection, Helpers){
// Main Index View
var IndexView = Backbone.View.extend({
el: "#content",
template: Helpers.template('index'),
initialize: function(){
this.questions = new QuestionsCollection();
this.questions.on('sync', this.render, this);
this.questions.fetch();
},
render: function(){
this.$el.html(this.template(this));
this.questions.each(this.addQuestion, this);
return this;
},
addQuestion: function(question){
var view = new IndexView.Question({ model: question });
view.render();
},
count: function(){
console.log(this);
return this.questions.length;
}
});
// Individual Question View
IndexView.Question = Backbone.View.extend({
render: function(){
// console.log(this.model);
}
});
return IndexView;
});
ここでは、すべてが期待どおりに機能しています。しかし今、コレクション内のモデルの数を返すヘルパー関数 count が必要です。そうすれば、次のようなものを印刷するため{{count}}
に使用できます。. しかし、私はスコープに問題があります。handle bar template
'There are 8 questions'
count
関数内では、これは を参照しますが、 は参照しwindow
ませんcollection
。count
として内部でこれへの参照を取得するにはどうすればよいですかquestion collection
。アプリでこれらのヘルパー関数の多くを使用する予定です。そのため、しっかりとした方法が必要です。
ありがとう。