2013-05-08 53 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