在getJSON完成之后实例化一个对象
Instantiate an object after getJSON is done
我想从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
被正确实例化。我尝试使用response
的done
方法来完成此操作。
所讨论的类:
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过滤器中进行验证。headlines
对象的list
属性应该包含来自文件的数据,但它总是未定义的。程序在headlines
对象的getRandom
方法中的这一行遇到异常:
var headlinePick = this.list[headlineNumber];
例外是Uncaught TypeError: Cannot read property 'NaN' of undefined
。
我不知道问题到底在哪里,也不知道从这里该怎么走。如有任何指导,我将不胜感激。
当直接从getJSON
调用时,this
并不意味着headlines
对象。
试题:
this.refreshContent = function() {
var self = this;
response = $.when($.getJSON(this.url,
function(data) {
self.fillFromJSON(data);
}
);
};
相关文章:
- 在 JavaScript 中,当我们实例化派生对象时,原型的函数隐藏在哪里
- 实例化一个javascript对象并在一行中填充其属性
- 为什么我在尝试实例化一个空的backbone.js视图时出现类型错误
- 在 Fabric.js 中只串化一个对象
- 是否可以在没有构造函数参数的情况下实例化空对象/对象
- 在另一个对象中实例化一个对象
- 如何在Javascript中实例化一个对象圈
- 实例化一个对象,使其可以与多个指令共享
- 有可能在TypeScript中实例化一个JavaScript对象吗?
- 无法在不同文件中实例化一个类的对象
- 在getJSON完成之后实例化一个对象
- 当你在JavaScript中实例化一个带有参数的新对象(1)时会发生什么?
- Flask——从外部实例化一个对象似乎没有做任何事情
- 在JavaScript中是否有一种方法可以实例化一个不一定是函数的对象
- 如何从.json文件实例化一个js对象
- 如何在另一个类(ClassB)中实例化一个类(ClassA),并在JavaScript中使用ClassA对象作为Clas
- 如何从现有的JS对象实例化一个相同的JS对象
- 在javascript中实例化一个对象
- 如何实例化一个具有由函数设置的属性的对象,即在正确的时间调用它们
- 你能在.NET中从JSON实例化一个对象实例吗