0

我想从 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是否被正确实例化。我尝试使用 的done方法response来完成此操作。

有问题的班级:

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 linter 中进行验证。对象的list属性headlines应该包含文件中的数据,但它始终是未定义的。headlines程序在对象方法内的这一行遇到异常getRandom

var headlinePick = this.list[headlineNumber];

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

我不确定问题到底出在哪里或从这里去哪里。任何指导将不胜感激。

4

1 回答 1

2

thisheadlines直接从getJSON.

尝试:

this.refreshContent = function() {
    var self = this;
    response = $.when($.getJSON(this.url,
      function(data) {
        self.fillFromJSON(data);
      }
    );
};
于 2013-05-08T22:19:49.827 回答