我正在尝试使用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