Backbone:TypeError:Undefined不是函数

时间:2015-01-14 21:38:40

标签: javascript backbone.js

我对Javascript和Backbone都非常陌生。基于几个教程,我编写了以下代码:

var app = app || {};

app.City = Backbone.Model.extend();

app.CityCollection = Backbone.Collection.extend({
    model: app.City,
    url: "http:127.0.0.1:8000/api/listing/city"
});

app.District = Backbone.Model.extend();

app.DistrictCollection = Backbone.Collection.extend({
    model: app.District,
    url: "http:127.0.0.1:8000/api/listing/district"
});

app.Advert = Backbone.Model.extend();

app.AdvertCollection = Backbone.Collection.extend({
    model: app.Advert,
    url: "http:127.0.0.1:8000/api/listing/advert"
});

app.AdvertListView = Backbone.View.extend({
    tagname:'table',

    intialize: function () {
        this.model.bind("reset", this.render, this);
    },

    render:function (eventName) {
        _.each(this.model.models, function (advert) {
            $(this.el).append(new AdvertListItemView({model:advert}).render().el);
        }, this);
        return this;
    }
});

app.AdvertListItemView = Backbone.View.extend({
    tagname:'td',
    template: _.template($('#advert-list-item').html()),

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

var AppRouter = Backbone.Router.extend({

    routes:{
        "":"list",
        "advert/:id":"advertDetails"
    },

    list:function() {
        this.app.AdvertList = new app.AdvertCollection();
        this.app.advertListView = new app.AdvertListView({model:this.advertList});
        this.app.AdvertList.fetch();
        $('#advert-list-item').html(this.advertListView.render().el);
    }
});

var app = new AppRouter();
Backbone.history.start();

当我尝试在浏览器中加载页面时收到以下错误消息:

未捕获的TypeError:undefined不是第61行中的函数。第61行如下:

this.app.AdvertList = new app.AdvertCollection();

我很感激我的错误。

1 个答案:

答案 0 :(得分:1)

你在这里遇到的问题是范围。您正在引用this.app.AdvertList,但this.app未定义。从列表功能中删除this

第61行的this指的是运行代码的对象。在这种情况下,该对象是AppRouter。由于Approuter.app.AdvertList未定义,因此您会收到该错误。