Backbone collection.each()不起作用

时间:2013-05-18 17:34:19

标签: javascript backbone.js

当我尝试使用Backbone的collection.each()方法时,我收到以下消息:

TypeError:Object function(){return parent.apply(this,arguments);没有方法'每个'

我正在从一些Jeffrey Way教程中学习Backbone;我为他输入了相同的代码,但由于某种原因它不起作用。

var Person = Backbone.Model.extend({
    defaults: {
        name: 'besim dauti',
        age: 15,
        occupation: 'web developer'
    }
});

var PeopleView = Backbone.View.extend({
    tagName: 'ul',

    render: function(){
        this.collection.each(function(person) {
            var personView = new PersonView({ model: person });
            this.$el.append(personView.render().el)
        }, this)
        return this;
    }
});

var PersonView = Backbone.View.extend({
    tagName: 'li',

    template: _.template( $('#personTemplate').html() ),

    render: function(){
        this.$el.html(this.template(this.model.toJSON()) );
        return this;
    }
});

var PeopleCollection = Backbone.Collection.extend({
    model: Person
});

var peopleCollection = new PeopleCollection([
    {
        name: 'besim',
        age: 25,
        occupation: 'web developer'
    },
    {
        name: 'gaurav',
        age: 25,
        occupation: 'web designer'
    },
    {
        name: 'jeffry',
        age: 27
    }
])

var peopleView = new PeopleView ({collection: PeopleCollection});
$(document.body).append(peopleView.render().el);

为什么.each()功能出现此问题?我输入相同的代码,对于Jeffrey,它按预期工作,但对我来说它显示了这个错误。感谢您的帮助。

2 个答案:

答案 0 :(得分:5)

您需要初始化PeopleCollection

请参阅:var peopleView = new PeopleView ({collection: PeopleCollection});

您传入的是原始构造函数,而不是它的实例。

你应该这样做:

var peopleCollection = new PeopleCollection(); // Create an instance of PeopleCollection
var peopleView = new PeopleView ({collection: peopleCollection}); // Pass it to peopleView

如果您熟悉OOP(面向对象编程),请将PeopleCollection视为一个类,将var peopleCollection = new PeopleCollection()视为该类的实例。您必须使用实例。

您在.each内也会遇到错误,因为您已将person大写。改为:

this.collection.each(function(person) {
   var personView = new PersonView({ model: person });
   this.$el.append(personView.render().el)
}, this)

答案 1 :(得分:1)

您的代码在jsfiddle中运行良好。

http://jsfiddle.net/puleos/kbLES/

var peopleView = new PeopleView ({collection: peopleCollection});
$(document.body).append(peopleView.render().el);

看起来您可能存在依赖性问题。你能在网页上发布你如何包含你的脚本吗?