繁体   English   中英

骨干这是未定义的

[英]Backbone this is undefined

我在主干网方面遇到了麻烦,并向几个人寻求帮助,但到目前为止还没有运气。

我创建一个这样的新收藏

let eventsCollection = new BandEvents({artist: 'Muse'});

在收藏中,我这样做

const BandEvents = Collection.extend({
    model: Artist,
    url: 'http://api.bandsintown.com/artists/' + this.artist + '/events.json?api_version=2.0&app_id=SomeID',

});

运行此代码时,在浏览器控制台中出现以下错误

Uncaught TypeError: Cannot read property 'artist' of undefined

因此, + this.artist +中的+ this.artist +是未定义的。 我不知道我在做什么错。

是未定义的,因为在此处设置url时不会实例化该集合。 如果需要动态设置,我建议使用url函数: http : //backbonejs.org/#Collection-url

这就是我解决的方法

我变了

let eventsCollection = new BandEvents({artist: 'Muse'});

let eventsCollection = new BandEvents($('#artist-input').val());

(我需要从输入字段中获得艺术家的名字)

并改变了

const BandEvents = Collection.extend({
    model: Artist,
    url: 'http://api.bandsintown.com/artists/' + this.artist + '/events.json?api_version=2.0&app_id=SomeID',

});

const BandEvents = Collection.extend({
    model: Artist,
    initialize: function (artist) {
        this.url = `http://api.bandsintown.com/artists/${artist}/events.json?api_version=2.0&app_id=ShowEvents`;
    }
});

为此,我使用ES6的模板文字

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM