2

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

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

我正在从一些 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,它按预期工作,但对我来说,它显示了这个错误。我感谢您的帮助。

4

2 回答 2

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)
于 2013-05-18T17:45:49.297 回答
1

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

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

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

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

于 2013-05-18T18:27:41.737 回答