我正在使用 jQuery 的 getJSON 方法。由于它是异步的,我在函数上使用 when 方法来调用它来知道何时可以运行下一个函数。下一个功能是使用 Handlebars 模板创建表格。我知道何时工作,因为模板已创建,但我没有获得所需的数据。
当使用 console.log 时,我看到附加到此的数组,但如果我说 this.objName 它是未定义的。那么promise/deferred只是表示请求成功了吗?有没有一种方法可以让我等待/观察数据?
(function () {
"use strict";
var TicketQueue = {
init: function (config) {
this.url = config.data;
this.template = config.template;
this.container = config.container;
$.when(this.fetch()).done(this.attachTemplate());
},
attachTemplate: function () {
var template = Handlebars.compile(this.template);
this.container.append(template(this.tickets));
},
fetch: function () {
var self = this;
$.getJSON(this.url, function (data) {
self.tickets = $.map(data.tickets, function (ticket) {
return ticket;
});
//self.attachTemplate();
});
}
};
TicketQueue.init({
template: $('#ticketQueueTpl').html(),
container: $("table.ticketQueue"),
data: "db/tickets.json"
});
}());
我有一个注释 self.attacheTemplate 确实有效,但我试图使该函数只是获取和初始化我的所有代码。
最佳答案
$.when()
需要 Deferred 作为参数,否则它会立即解析。由于您没有从this.fetch()
返回 AJAX promise ,因此会表现出后一种行为。 返回来自this.fetch()
的 AJAX 调用。fetch: function () { var self = this; return $.getJSON(this.url, function (data) { self.tickets = $.map(data.tickets, function (ticket) { return ticket; }); //self.attachTemplate(); }); }
您将
this.attachTemplate()
的结果传递给then()
,而不是函数本身。你想做的事;$.when(this.fetch()).done(function () { this.attachTemplate() }.bind(this));
注意,我在其中附加了一个额外的
bind()
;这是因为this
的值在我们使用的匿名函数中丢失了。
话虽如此,您甚至根本不需要 $.when()
; $.when()
适合将多个 Deferred 组合成一个 Deferred。只需使用;
this.fetch().done(function () {
this.attachTemplate();
}.bind(this));
关于jQuery promise /延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22260482/