getJSON完成后实例化一个对象

时间:2013-05-08 22:16:03

标签: javascript jquery ajax oop

我想从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网络标签,确保JSON文件没有任何问题。它提供200响应并在JSON linter中验证。 list对象的headlines属性应包含文件中的数据,但始终未定义。该程序在headlines对象的getRandom方法中的此行上遇到异常:

var headlinePick = this.list[headlineNumber];

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

我不确定问题的确切位置或从何处开始。任何指导都将不胜感激。

1 个答案:

答案 0 :(得分:2)

直接从this调用

headlines并不代表getJSON对象。

尝试:

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