2013-05-08 41 views
0

我想从jQuery getJSON调用中另一个对象获取的数据实例化新对象。我发现了承诺对象,并且我认为我可以用它来实现这一点。下面是我实现的:getJSON完成后实例化对象

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网络选项卡,以确保没有什么JSON文件错误。它给出了一个200响应,并在JSON linter中进行验证。 headlines对象的list属性应包含来自该文件的数据,但它始终未定义。

var headlinePick = this.list[headlineNumber]; 

唯一的例外是Uncaught TypeError: Cannot read property 'NaN' of undefined:该项目在此线路上headlines对象的getRandom方法里面打一个例外。

我不确定问题的确切位置或从哪里去。任何指导将不胜感激。

回答

2

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

尝试:

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

或者更简单地说'响应= $。当($的getJSON(this.url,this.fillFromJSON.bind(本)));' – bmceldowney 2013-05-08 22:36:20

+0

这是问题。谢谢你们俩! – raddevon 2013-05-08 23:53:20