【发布时间】:2013-01-20 02:17:40
【问题描述】:
我正在尝试使用 require.js、AMD 和车把作为模板构建一个 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;
});
这里一切都按预期工作。但现在我想要一个辅助函数 count 来返回集合中模型的数量。这样我就可以在我的handle bar template 中使用{{count}} 来打印类似的东西。 'There are 8 questions'。但我的范围有问题。
在count 函数中,这指的是window,而不是collection。我将如何在count 中以question collection 引用此内容。我计划在我的应用程序中使用许多这些辅助功能。所以需要一些可靠的方法来做到这一点。
谢谢。
【问题讨论】:
-
为什么要将视图传递给模板函数?为什么不给模板函数视图的数据(即集合),这样你甚至不需要帮助器?
-
另一种选择是将计数函数放入集合中,并将其称为 this.collection.count()。
-
@DennisRongo 但是您将如何在模板中使用它?我想在
{count}这样的模板中使用它。 -
通常的做法是说
this.template({ collection: this.collection.toJSON() })之类的东西,然后你在模板中的{{collection}}中有一个简单的数组,你可以问它有多长而不用担心方法绑定。跨度> -
您可以将您的收藏和计数作为一个对象传递到您的模板中。例如,this.template{ coll: this.collection, count: this.collection.count()}。我建议将计数包含在集合中的原因是,它将视图从具有特定集合中解放出来。这使您的视图灵活且可重复用于不同的集合。
标签: backbone.js requirejs handlebars.js