在带有Backbone的View中显示集合项的数量

时间:2014-04-24 06:46:16

标签: javascript backbone.js single-page-application backbone-views backbone-collections

如何显示集合中的项目数?我尝试使用collection.models.lengthcollection.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;

});

1 个答案:

答案 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;