2013-05-08 3 views
0

jQuery getJSON 호출에서 다른 객체가 가져온 데이터에서 새 객체를 인스턴스화하려고합니다. 나는 약속의 물건을 발견했고, 나는 이것을 성취하는데 사용할 수있을 것이라고 생각했다. HeadlineList 객체가 인스턴스화 될 때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(); 
} 

, 그것은해서 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 객체 인스턴스화 이후 클래스의 인스턴스 : 거기에 아무것도 확실하게 나는 크롬 DevTools로 네트워크 탭을 검토 한

// 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)); 
}); 

을 JSON 파일에 문제가 있습니다. 그것은 200 응답을 제공하고 JSON linter에서 유효성을 검사합니다. headlines 개체의 list 속성은 파일의 데이터를 포함해야하지만 항상 정의되지 않습니다.

var headlinePick = this.list[headlineNumber]; 

예외가 Uncaught TypeError: Cannot read property 'NaN' of undefined입니다 :이 프로그램은 headlines 객체의 getRandom 방법 안쪽이 라인에 예외를 안타.

어디서 문제가 발생했는지 정확히 알지 못합니다. 모든 지침은 크게 감사하겠습니다.

답변

2

thisgetJSON에서 직접 호출 할 때 headlines 개체를 의미하지 않습니다.

시도 :

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

이상 단순히'응답 = $ .when ($해서 getJSON (this.url, this.fillFromJSON.bind (이)).) 문제가 있었다' – bmceldowney

+0

. 둘 다 감사합니다! – raddevon

관련 문제