在getJSON完成之后实例化一个对象

Instantiate an object after getJSON is done

本文关键字:实例化 一个对象 之后 getJSON      更新时间:2023-09-26

我想从jQuery getJSON调用中另一个对象获取的数据实例化一个新对象。我发现了promise对象,我想我可以用它们来完成这个任务。下面是我的实现:

function HeadlineList(url) {
    this.url = url;
    this.checkEmpty = function() {
        if (this.quantity === 0) {
            this.refreshContent();
        }
    };
    this.getRandom = function(remove) {
        var headlineNumber = Math.floor(Math.random()*this.quantity);
        var headlinePick = this.list[headlineNumber];
        if (remove) {
            this.deleteHeadline(headlineNumber);
        }
        return headline;
    };
    this.getHeadline = function(number, remove) {
        var headlinePick = this.list[number]
        if (remove) {
            this.deleteHeadline(number);
        }
        return headline;
    };
    this.deleteHeadline = function(number) {
        this.list.splice(number, 1);
        this.quantity -= 1;
    };
    this.fillFromJSON = function(data) {
        this.list = data.headlines;
        this.quantity = this.list.length;
    };
    // Here's where I create the promise object. 'response' is globally 
    // scoped so my other objects can get to it.
    this.refreshContent = function() {
        response = $.when($.getJSON(this.url, this.fillFromJSON));
    };
    this.refreshContent();
}

HeadlineList对象实例化时,它使用getJSON获取数据。这个AJAX请求存储在response全局变量中,因此我可以确保稍后完成它。在此之后,我想要创建一个不同的对象,但数据依赖于这个HeadlineList被正确实例化。我尝试使用responsedone方法来完成此操作。

所讨论的类:

function Headline(object) {
    this.title = object.title;
    this.url = object.url;
    this.onion = object.onion;
    this.isOnion = function(){
        return this.onion;
    }
}

和实例化HeadlineList对象后的类的实例化:

// headlines is an instance of HeadlineList with the URL of my JSON file. 
// It should (and does) make the request when instantiated.
headlines = new HeadlineList('js/headlines.json');
// Instantiating the headline after the AJAX request is done. Passing
// a random headline from the HeadlineList object to the constructor.
response.done(function() {
    headline = new Headline(headlines.getRandom(true));
});

我已经看了Chrome DevTools Network选项卡,以确保JSON文件没有任何问题。它给出一个200响应,并在一个JSON过滤器中进行验证。headlines对象的list属性应该包含来自文件的数据,但它总是未定义的。程序在headlines对象的getRandom方法中的这一行遇到异常:

var headlinePick = this.list[headlineNumber];

例外是Uncaught TypeError: Cannot read property 'NaN' of undefined

我不知道问题到底在哪里,也不知道从这里该怎么走。如有任何指导,我将不胜感激。

当直接从getJSON调用时,this并不意味着headlines对象。

试题:

this.refreshContent = function() {
    var self = this;
    response = $.when($.getJSON(this.url,
      function(data) {
        self.fillFromJSON(data);
      }
    );
};