如何显示集合中的项目数?我尝试使用collection.models.length
或collection.length
无效。我甚至在名为Backbone.Collection
的{{1}}中创建了一个方法来返回集合的长度,但没有任何反应。
模板:
count()
收集:
<p>you have <span class="caller-num">0</span> missed calls.</p>
未接来电查看:显示未接来电数量
// callers collection
define([
'jquery',
'underscore',
'backbone',
'models/caller'
], function($, _, Backbone, Caller) {
var CallersList = Backbone.Collection.extend({
model: Caller,
url: 'js/json/callers.json',
// had to do this because it's the 'callers' key that has the array of objects, the json
parse: function(data) {
return data.callers;
},
count: function() {
return this.length;
}
});
return CallersList;
});
APPVIEW:
define([
'jquery',
'underscore',
'backbone',
'collections/callers-list',
'text!templates/missed-calls-number-template.html'
], function($, _, Backbone, CallersList, missedCallsNumTemplate) {
var MissedCallsNumberView = Backbone.View.extend({
el: '.number-of-callers',
template: _.template(missedCallsNumTemplate),
initialize: function() {
var callers = new CallersList;
this.$el.find('.caller-num').text(callers.count());
//this.$el.find('.caller-num').text($('.caller').length); /* this doesn't work either */
},
render: function() {
this.$el.html(this.template(this.model));
return this;
}
});
return MissedCallsNumberView;
});
答案 0 :(得分:0)
length
应该在MissedCallsNumberView
render: function() {
this.$el.html(this.template(this.model));
this.$el.find('.caller-num').text(callers.length);
return this;
}
我认为问题在于您在视图的初始化中创建了一个新集合。您可能想要在创建视图时传递的集合:
var callers = this.collection;