我正在嘗試使用require.js,AMD和模板的handlebars構建一個Backbone應用程序。 這是我的索引視圖的代碼。將'this'引用傳遞給Backbone函數
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;
});
這裏一切都按照原理進行工作。但是現在我想要一個輔助函數計數,它將返回集合中模型的數量。這樣我可以在handle bar template
中使用{{count}}
來打印類似的東西。 'There are 8 questions'
。但是我的範圍有問題。
裏面count
功能這是指window
但不是collection
。我如何能夠在count
內部獲得question collection
的參考。我打算在我的應用程序中使用這些輔助函數。所以需要一些可靠的方法來做到這一點。
THanks。
爲什麼你傳遞視圖模板函數?爲什麼不給模板函數視圖的數據(即集合),以至於你甚至不需要幫助器? –
另一種選擇是將count函數放入集合中,並將其作爲this.collection.count()引用。 –
@DennisRongo但你將如何在模板中使用?我想在像{count}'這樣的模板中使用它。 – Subash